关于Spring,default-autowire-candidates属性的作用验证

来源:互联网 发布:网络是把双刃剑英语 编辑:程序博客网 时间:2024/06/01 08:42

在查看轻量级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
原创粉丝点击