一直有这样一个规则:所有在spring中注入的bean都建议定义成私有的域变量。
package com.cuihs;
public class Boss {
private Car car;
private Office office;
// 省略 get/setter
@Override
public String toString() {
return "car:" + car + "/n" + "office:" + office;
}
}
下面是使用传统xml这个工作的配置文件beans.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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-2.5.xsd">
<bean id="boss" class="com.cuihs.Boss">
<property name="car" ref="car"/>
<property name="office" ref="office" />
</bean>
<bean id="office" class="com.cuihs.Office">
<property name="officeNo" value="002"/>
</bean>
<bean id="car" class="com.cuihs.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
测试代码:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnoIoCTest {
public static void main(String[] args) {
String[] locations = {"beans.xml"};
ApplicationContext ctx =
new ClassPathXmlApplicationContext(locations);
Boss boss = (Boss) ctx.getBean("boss");
System.out.println(boss);
}
}
@Autowired
Spring 2.5引入了@Autowired注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
package com.cuihs;
import org.springframework.beans.factory.annotation.Autowired;
public class Boss {
@Autowired
private Car car;
@Autowired
private Office office;
…
}
<?xml version="1.0" encoding="UTF-8" ?>
<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-2.5.xsd">
<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
<!-- 移除 boss Bean 的属性注入配置的信息 -->
<bean id="boss" class="com.cuihs.Boss"/>
<bean id="office" class="com.cuihs.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.cuihs.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
这样,当Spring窗口启动时,AutowiredAnnotationBeanPostProcessor将扫描Spring容器中所有Bean,当发现Bean中拥有@Autowired注释时就找到和其匹配(默认按类型匹配)的Bean,并注入到对应的地方中去。
当然,也可以通过@Autowired对方法或构造函数进行标注,如果构造函数有两个入参,分别是bean1和bean2,@Autowired将分别寻找和它们类型匹配的Bean,将它们作为入参来创建。
最后欢迎大家访问我的个人网站:1024s