天天看點

spring應用手冊-IOC(XML配置實作)-(32)-context:component-scan的annotation-config屬性

戴着假發的程式員出品

context:component-scan的annotation-config屬性

spring應用手冊(第一部分)

annotation-config預設是true,完成了context:annotation-config元素的工作,如果是true就開啟了屬性自動注入的功能,如果是false就是關閉屬性自動注入的功能。

案例:

我們建立兩個類Person和Student,并且都交個spring管理,在Person中自動注入Student。

/**
 * @author 戴着假發的程式員
 *  
 * @description
 */
@Component
public class Student{
}
           
/**
 * @author 戴着假發的程式員
 *  
 * @description
 */
@Component
public class Person {
    @Autowired
    private Student student;
    public void shwoStu(){
        System.out.println(student);
    }
}
           

配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan annotation-config="false" base-package="com.boxuewa.dk.demo5">
    </context:component-scan>
</beans>
           

測試:

@Test
public void testAnnotationConfig(){
    ApplicationContext ac =
            new ClassPathXmlApplicationContext("applicationContext-demo9.xml");
    Person bean = ac.getBean(Person.class);
    bean.shwoStu();
}
           

結果:

spring應用手冊-IOC(XML配置實作)-(32)-context:component-scan的annotation-config屬性

我們發現Person中的Stduent屬性不能注入了。