Spring provides a mechanism where it can automatically handle the injection of properties and referred objects without defining them in xml files by using Spring Annotations. Listing them below:
@Autowired
@Resource
@PostConstruct
@PreDestroy
@Qualifier
@Required
@Bean
@Component
@Service
@Repository
Where to apply annotations
1. @Autowired:
@autowired annotaion is applied to "traditional" setter methods, constructors and fields.
@autowired annotaion is applied to methods with arbitrary names and/or multiple arguments.
@autowired annotaion is applied to field or method that expects an array,collections and maps of that type
2. @Resource:
@Resource takes a 'name' attribute, and by default Spring will interpret that value as the bean name to be injected.
If no name is specified explicitly, then the default name will be derived from the name of the field or setter method:
In case of a field, it will simply be equivalent to the field name
In case of a setter method, it will be equivalent to the bean property name
3. @PostConstruct:
@PostConstruct is a JSR-250 annotaion.
This annotation is applied to a method to indicate that it should be invoked after all dependency injection is complete.
4. @PreDestroy:
This is applied to a method to indicate that it should be invoked before the bean is removed from the Spring context, i.e. just before its destroyed.
5. @Qualifier:
This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument.
It can also be specified on individual constructor arguments or method parameters
6. @Required:
Only one annotated constructor per-class may be marked as required, but multiple non-required constructors can be annotated.
Prefer the use of @Autowired's required attribute over the @Required annotation. The required attribute indicates that the property is not required for autowiring purposes, simply skipping it if it cannot be autowired.
7. @Bean:
@Bean is a method-level annotation and a direct analog of the XML element.
The annotation supports most of the attributes offered by , such as: init-method, destroy-method, autowiring, lazy-init, dependency-check, depends-on and scope.
8. @Component:
@Component is a generic stereotype for any Spring-managed component.
It is used to auto-detect and auto-configure beans using classpath scanning.
9. @Service:
@Service serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
If you are making a decision between using @Component and @Service, @Service is clearly the better choice for your service-layer.
10. @Repository:
@Repository is already supported as a marker for automatic exception translation in your persistence layer.
0 Comment(s)