An alternative to XML configuration is annotation-based configuration, which relies on bytecode metadata to connect components instead of angle-bracket declarations. Instead of using XML to describe the bean binding tool, the developer wraps the configuration into the bean class itself using annotations for the corresponding class, method, or field declaration. As mentioned in the subsection Example: AutowiredAnnotationBeanPostProcessor, usingBeanPostProcessor in combination with annotations is a common means of extending the Spring IoC container. For example, Spring 2.0 introduced the ability to force required properties using the @Required annotation. Spring 2.5 allowed the same general approach to manage dependency injection using Spring. Essentially, the @Autowired annotation provides the same capabilities as described in the section "Automatic detection and binding interacting objects, but with finer control and wider applicability. Spring 2.5 also added support for JSR-250 annotations such as @PostConstruct and @PreDestroy. For Spring 3.0, support has been added for JSR-330 (Dependency Injection for Java) annotations contained in the javax.inject package, such as @Inject and @Named.
Dependency injection using annotations occurs before dependency injection using XML. Thus, XML configuration overrides property annotations through both approaches.
As usual, you can register postprocessors as separate bean definitions, but they can also be registered implicitly by including the following tag in your Spring XML configuration (note the inclusion of the context namespace):
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
The <context:annotation-config/> element implicitly registers the following postprocessors:
<context:annotation-config/> only looks for annotations for beans in the same application context in which it is defined. This means that if you put <context:annotation-config/> in the WebApplicationContext for the DispatcherServlet, it will check for the presence of @Autowired beans only in your controllers, not in services.
GO TO FULL VERSION