关于Spring,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-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>


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应该是候选者,即匹配则被包含。不匹配的排除在外。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值