最基础的装配
xml配置
<bean id="helloWorld" class="priv.dengjl.spring.HelloWorld">
<property name="message" value="Hello World!" />
</bean>
ioc容器中获取
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
嵌套bean的装配
xml配置
<bean id="helloWorld2" class="priv.dengjl.spring.HelloWorld">
<property name="message" value="china" />
</bean>
<bean id="innerBean" class="priv.dengjl.spring.InnerBean">
<property name="name" value="dengjl" />
<property name="helloWorld" ref="helloWorld2" />
</bean>
bean文件
private String name;
private HelloWorld helloWorld;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public HelloWorld getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
}
}
ioc容器中获取
ApplicationContext context = new ClassPathXmlApplicationContext("InnerBeans.xml");
InnerBean obj = (InnerBean) context.getBean("innerBean");
log.error(obj.getName());
obj.getHelloWorld().getMessage();
集合的装配
xml配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="assembly" class="priv.dengjl.spring.ComplexAssembly">
<property name="id" value="1" />
<property name="list">
<list>
<value>zhangsan-1</value>
<value>lisi-2</value>
<value>wangwu-3</value>
<value>zhaoliu-4</value>
</list>
</property>
<property name="map">
<map>
<entry key="shuxue" value="100"/>
<entry key="yuwen" value="34"/>
<entry key="yingyu" value="20"/>
</map>
</property>
<property name="props">
<props>
<prop key="prop1">1</prop>
<prop key="prop2">2</prop>
<prop key="prop3">3</prop>
</props>
</property>
<property name="set">
<set>
<value>set-1</value>
<value>set-2</value>
<value>set-3</value>
</set>
</property>
<property name="array">
<array>
<value>array-1</value>
<value>array-2</value>
<value>array-3</value>
</array>
</property>
</bean>
</beans>
bean文件
public class ComplexAssembly {
private long id;
private List<String> list;
private Map<String, String> map;
private Properties props;
private Set<String> set;
private String[] array;
// seter geter
}
ioc容器中获取
ApplicationContext context = new ClassPathXmlApplicationContext("assembly.xml");
ComplexAssembly obj = (ComplexAssembly) context.getBean("assembly");
log.error("{}", obj.getId());
log.error("{}", obj.getList());
log.error("{}", obj.getMap());
log.error("{}", obj.getProps());
log.error("{}", obj.getSet());
log.error("{}", obj.getArray());