首页IT科技spring基于注解注入(Spring IOC官方文档学习笔记(九)之基于注解的容器配置)

spring基于注解注入(Spring IOC官方文档学习笔记(九)之基于注解的容器配置)

时间2025-08-05 17:25:38分类IT科技浏览4108
导读:1.基于注解的配置与基于xml的配置...

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

未完待续...

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
智能原创自动写作工具(使用AI在线文章伪原创工具,让文章更具独特风格)