本文实例讲述了Spring Bean基本管理。分享给大家供大家参考,具体如下:
一、使用setter方式完成依赖注入
下面是Bean和beans-config.xml文件。
public class HelloBean { private String helloWord; //...省略getter、setter方法 }<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://e</value> </list> </property> <property name="someObjArray"> <list> <ref bean="some1"/> <ref bean="some2"/> </list> </property> <property name="someList"> <list> <value>ListTest</value> <ref bean="some1"/> <ref bean="some2"/> </list> </property> <property name="someMap"> <map> <entry key="MapTest"> <value>Hello!Justin!</value> </entry> <entry key="someKey1"> <ref bean="some1"/> </entry> </map> </property> </bean> </beans>public class SpringDemo { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext( "beans-config.xml"); SomeBean someBean = (SomeBean) context.getBean("someBean"); // 取得数组型态依赖注入对象 String[] strs = (String[]) someBean.getSomeStrArray(); Some[] somes = (Some[]) someBean.getSomeObjArray(); for(int i = 0; i < strs.length; i++) { System.out.println(strs[i] + "," + somes[i].getName()); } // 取得List型态依赖注入对象 System.out.println(); List someList = (List) someBean.getSomeList(); for(int i = 0; i < someList.size(); i++) { System.out.println(someList.get(i)); } // 取得Map型态依赖注入对象 System.out.println(); Map someMap = (Map) someBean.getSomeMap(); System.out.println(someMap.get("MapTest")); System.out.println(someMap.get("someKey1")); } }希望本文所述对大家Java程序设计有所帮助。