default-autowire-candidates属性的作用验证

在查看轻量级java_EE企业应用实战(李刚 著)看到default-autowire-candidates的作用时,原文描述是这样的:
我们还可通过<beans/>元素中制定default-autowire-candidates属性来对一批Bean进行限制,将这批Bean排除这自动装配之外。default-autowire-candidates属性的值允许使用模式字符串,例如我们制定default-autowire-candidates=“*abc”,则所有以“abc”结尾的Bean都将被排除在自动装配之外。不仅如此,该属性甚至可以指定多个模式字符串,这样所有匹配任一模式字符串的Bean都将被排除在自动装配之外。

当看见这段描述的时候产生了怀疑,此属性的字面意思应该是自动装配的候选者,而不是排除者。遂进行验证:

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/```
[spring](http://lib.csdn.net/base/javaee)-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd " ** default-autowire-candidates="*Axe"** ><bean id="chinese" class="myspring.Chinese"  autowire="byType"><bean id="steelAxe" class="myspring.SteelAxe"></bean>
</beans>

```java
public class Chinese {    private Axe axe;    public void setAxe(Axe axe) {        this.axe = axe;    }    @Override    public void useAxe() {        System.out.println(axe.chop());    }}

测试
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");Person person = ctx.getBean("chinese", Person.class);person.useAxe();
执行正常。说明steelAxe并未被排除在外。而是被正常的自动装配了。

修改default-autowire-candidates:**** default-autowire-candidates="Axe2"*
再次执行测试:
Exception in thread "main" Java.lang.NullPointerException at myspring.Chinese.useAxe(Chinese.java:30) at myspring.SpringTest.main(SpringTest.java:58)
空指针,说明chinese的依赖axe未被注入,为空。所以执行Chinese.useAxe方法时,报空指针错。

综上测试, default-autowire-candidates应该是候选者,即匹配则被包含。不匹配的排除在外。**
关于Spring,default-autowire-candidates属性的作用验证

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 文章作者:Tyan博客:noahsnail.com 3.4 依赖 标准企业应用不会由一个对象(或Spring用语中...
    SnailTyan阅读 4,933评论 0 1
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 9,776评论 2 7
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,092评论 19 139
  • Spring简介: Spring是一个IOC(DI)和AOP容器框架: 轻量级:Spring是非侵入性的,基于开发...
    JHMichael阅读 3,730评论 0 3
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,712评论 1 133

友情链接更多精彩内容