1.基于注解的配置与基于xml的配置
(1) 在xml配置文件中,使用<context:annotation-config></context:annotation-config>标签即可开启基于注解的配置,如下所示,该标签会隐式的向容器中添加ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor这5个后置处理器,用于处理注解
<beans ....>
<!-- 开启基于注解的配置,该标签不常用,常用下面的<context:component-scan />标签 -->
<context:annotation-config></context:annotation-config>
<!-- 开启注解扫描,它不仅有着 <context:annotation-config />标签相同的效果,还提供了一个base-package属性用来指定包扫描路径,将路径下所扫描到的bean注入到容器中 -->
<!-- <context:component-scan base-package="cn.example.spring.boke"></context:component-scan> -->
</beans>
(2) Spring同时支持基于注解的配置与基于xml的配置,可以将两者混合起来使用;注解配置会先于xml配置执行,因此,基于xml配置注入的属性值会覆盖掉基于注解配置注入的属性值,如下所示
//定义一个普通bean
@Component(value = "exampleA")
public class ExampleA {
//通过注解,注入属性值
@Value("Annotation injected")
private String str;
public void setStr(String str) {
this.str = str;
}
public String getStr() {
return str;
}
}
<!-- xml配置文件 -->
<beans ....>
<context:component-scan base-package="cn.example.spring.boke"></context:component-scan>
<!-- 通过xml,注入属性值,注意:这里bean的id与上面基于注解所提供的bean的id是一致的 -->
<bean id="exampleA" class="cn.example.spring.boke.ExampleA">
<property name="str" value="xml inject"></property>
</bean>
</beans>
//测试,打印结果为 xml inject,证明注解方式会先于xml方式执行
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("boke/from.xml");
System.out.println(((ExampleA) ctx.getBean("exampleA")).getStr());
2.@Required
(1) @Required注解用于setter方法上,表示某个属性值必须被注入,若未注入该属性值,则容器会抛出异常,从Spring 5.1版本开始,该注解已被弃用,Spring目前推荐使用构造函数注入来注入这些非空依赖项,如下所示
//ExampleA有一个非空属性str
public class ExampleA {
private String str;
@Required
public void setStr(String str) {
this.str = str;
}
}
<!-- xml配置文件 -->
<beans ....>
<context:annotation-config></context:annotation-config>
<bean id="exampleA" class="cn.example.spring.boke.ExampleA">
<!-- 必须要设置str属性值,如果将下面这条标签注释掉,那么启动时容器会抛出异常 -->
<property name="str" value="must"></property>
</bean>
</beans>
3.@Autowired
(1) @Autowired可用于构造函数上,用于注入非空依赖项,如下
//有两个普通的bean: ExampleA和ExampleC
@Component
public class ExampleA { }
@Component
public class ExampleC { }
//例一:此时ExampleB有且仅有一个构造函数,那么对于该构造函数,加不加@Autowired都一样,因为Spring只能通过该构造函数来创建ExampleB对象
@Component
public class ExampleB {
//@Autowired //写不写都一样
public ExampleB(ExampleA exampleA) {
System.out.println("注入:" + exampleA);
}
}
//例二:此时ExampleB有多个构造函数,那么我们必须使用@Autowired来注解其中某一个构造函数,以此来指定容器在创建ExampleB对象时使用哪个构造函数
@Component
public class ExampleB {
public ExampleB(ExampleA exampleA) {
System.out.println("注入:" + exampleA);
}
//如果注释掉该@Autowired注解,启动容器时Spring会抛出异常,因为它不知道该选择哪个构造函数
//由于该构造函数添加了@Autowired注解,因此容器会选择这个构造函数来创建ExampleB对象
@Autowired
public ExampleB(ExampleC exampleC) {
Syst