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

未完待续...

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/shame11/p/17053881.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!