About <context:annotation-config/> configuration in Spring

About <context:annotation-config/> configuration in Spring

  When we need to use BeanPostProcessor, it is clumsy to define these beans directly in the Spring configuration file, for example:
  using @Autowired annotation, the Bean of AutowiredAnnotationBeanPostProcessor must be declared in the Spring container in advance :

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
  With @Required annotation, you must declare the Bean of RequiredAnnotationBeanPostProcessor:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/ >
  Similarly, using @Resource, @PostConstruct, @PreDestroy annotations, you must declare CommonAnnotationBeanPostProcessor; using @PersistenceContext annotation, you must declare PersistenceAnnotationBeanPostProcessor beans.
  Such a declaration is too inelegant, and Spring provides us with a very convenient way to register these BeanPostProcessors, that is, using <context:annotation-config/> to implicitly register AutowiredAnnotationBeanPostProcessor, RequiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor and PersistenceAnnotationBeanPostProcessor with the Spring container. BeanPostProcessor. As follows:

<context:annotation-config/>
  In addition, when we use annotations, we generally configure the scan package path option:

<context:component-scan base-package="pack.pack"/>
  This configuration item also includes automatic Inject the function of the above processor, so when using <context:component-scan/>, <context:annotation-config/> can be omitted.


Note:
Before using the context namespace in a configuration file, the context namespace must be declared in the <beans> element.

Copy code
<?xml version="1.0" encoding="UTF-8"?> 
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context" 
    ...
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    ...
        <context:annotation-config/>
    </beans>
复制代码

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326662471&siteId=291194637