There seem to be multiple XML tags for telling Spring to use annotations:
I would think tags 1 and 2 could be combined into one. So I don't know why they are separated.
For reasons of backwards compatibility. Old Spring apps have to keep working, and merging the tags (which were introduced in different versions of Spring) would break that by changing the default behaviour.
Tags 3 and 4 seem redundant to 1 and 2.
See above. The 4 tags do slightly different, but complimentary things. Yes, if Spring were designed from scratch, there would be fewer of them, but the functionality needs to remain seperate.
To summarise:
<context:annotation-config/>
enables annotation support in the context. This was added as part of Java 5 support, at a time when Spring still supported Java 1.4
<context:component-scan base-package="org.example" />
enables automatic scanning and configuration of beans, instead of using explicit declarations. This was added in Spring 2.5.
<mvc:annotation-driven />
is an odd one. It is not required in order to support annotated controller (those work by default). What it does is to actually disable the old style of non-annotated controller, as well as adding support for things like JSON. This is required because older apps still use the older controller style.
<tx:annotation-driven>
is required because Spring supports many different styles of transaction demarcation, one of which is the annotation style. This is most popular style, but by no means the only one.
Difference between annotation-config
and component-scan
a) <context:annotation-config/>
only looks for annotations on beans in the same application context in which it is defined. This means that, if you put <context:annotation-config/>
in a WebApplicationContext for a DispatcherServlet, it only checks for @Autowired beans in your controllers, and not your services. See Section 15.2, “The DispatcherServlet” for more information.
b) Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext. To autodetect these classes and register the corresponding beans requires the inclusion of the component-scan
element in XML where 'basePackage' would be a common parent package (or alternatively a comma-separated list could be specified that included the parent package of each class).
tx:annotation-driven
You do provide the transaction-manager instace directly within element. annotation-config
and component-scan
won't.
mvc:annotation-driven
This tag registers the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans that are required for Spring MVC to dispatch requests to @Controllers. The tag configures those two beans with sensible defaults based on what is present in your classpath. Read more at Spring doc.