4. Annotation-based Bean Configuration

[Note]Draft

This is a first draft of this chapter. It is technically accurate, but not in the style or state of the final revision.

Spring 2.5 has added extensive support for annotation-based configuration. Java annotations were added in Java 5, so Java 5 or higher must be used to take advantage these configuration options. Before Spring 2.5, there was annotation support in some areas, but it's been greatly enhanced in the latest release. Classes can be annotated to identify them as eligible to be registered as beans in the IoC container. Constructors, fields, methods, and parameters can be autowired by name or type. The basics of this have already been covered in the previous chapter, but we will go into more detail on all the different annotation-based configuration options.

4.1 Bean Creation

As covered in the previous chapter, classes can be annotated and then when they are discovered they will be registered as a bean in the IoC container. The @Component annotation has already been covered, but there are also three other default annotations that can indicate a class should be registered as a bean. They are @Controller, @Repository, and @Service.

Table 4.1. Annotations from org.springframework.stereotype

AnnotationSince VersionTargetDescription
@ComponentSpring 2.5Class Indicates this class is eligible for registration as a Spring bean when detected by a classpath scanner (context:component-scan).
@ControllerSpring 2.5Class Indicates this class is a Web Controller eligible for registration as a Spring bean when detected by a classpath scanner (context:component-scan). It is a specialized form of @Component.
@RepositorySpring 2.0Class Indicates this class is a Repository (DAO) eligible for registration as a Spring bean when detected by a classpath scanner (context:component-scan). It is a specialized form of @Component.
@ServiceSpring 2.5Class Indicates this class is a Service (business service facade) eligible for registration as a Spring bean when detected by a classpath scanner (context:component-scan). It is a specialized form of @Component.


Scope

The @Scope annotation can be used to set the scope for an annotation-based configuration, but a completely custom scope resolver can be used by setting the scope-resolver attribute with an implementation of org.springframework.context.annotation.ScopeMetadataResolver.

Table 4.2. Annotations from org.springframework.context.annotation

AnnotationSince VersionTargetDescription
@ScopeSpring 2.5Class Indicates the scope of the bean.