Spring annotations

Learn about the most widely used spring annotations. In this tutorial, we will briefly cover the important annotations which are provided by spring core to define beans and create complex application context configurations.

1. Bean annotations

Given list of annotations are used to define beans in spring and to control their registration preferences in application context.

AnnotationDescription
@BeanA method-level annotation used to declare a spring bean. When configuration execute annotated method, it registers the return value as a bean within a BeanFactory.

By default, the bean name will be the same as the method name. To customize the bean name, use its ‘name’ or ‘value’ attribute.

@Bean
EmployeeService employeeService() 
{
    return new EmployeeServiceImpl();
}
@ComponentIndicates that an annotated class is a “component” and will be auto-detected when using annotation-based configuration and classpath scanning.

To use this annotation, apply it over class as below:

@Component
public class EmployeeDAOImpl 
		implements EmployeeDAO {
    ...
}
@RepositoryAn specialization of the @Component annotation. In addition to importing the annotated DAO classes into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Repository
public class EmployeeDAOImpl 
		implements EmployeeDAO
{
    //...
}
@ServiceAn specialization of the @Component annotation. It indicates that a class is a “Business Service Facade” or something similar.

@Service ("employeeManager")
public class EmployeeManagerImpl 
		implements EmployeeManager
{
    @Autowired
    EmployeeDAO dao;
    
    ...
}
@ControllerAn specialization of the @Component to annotate controllers (e.g. a web controller). It used in combination with annotated handler methods based on the RequestMapping annotation.

@Controller ("employeeController")
public class EmployeeController 
{
	...
}
@Qualifier During autowiring, if more than one bean of the same type is available in the container then container will throw runtime exception. To fix this problem, we have to specifically tell spring that which bean has to be injected using this annotation.

In given example, if there are two beans of type Repository then on runtime, the bean with name ‘fsRepository’ will be injected.

public class EmployeeService {
      
    @Autowired
    @Qualifier("fsRepository")
    private Repository repository;
}
@AutowiredMarks a constructor, field, setter method, or config method as to be autowired by dependency injection. We can mark whether the annotated dependency is required (mandatory to populate) or not using it’s ‘required’ attribute. By default, its value is ‘true’.

public class EmployeeService {
      
    @Autowired
    private EmployeeDao dao;
}
@RequiredDefault bean autowiring checks only that dependency has been set. It does not checks whether the assigned value is null or not. Using @Required, we can check if values set are non-null. It has been deprecated now.
@Value Applicable at the field or method/constructor parameter level, and indicates a default value expression for the affected argument.

public class SomeService {
      
    @Value("${ENV}")
    private String environment;
}
@Lazy Indicates whether a bean is to be lazily initialized. By default, in spring DI, eager initialization will occur.

When applied over any bean, initialization of that bean will not happen until referenced by another bean or explicitly retrieved from the enclosing BeanFactory.

public class SomeService {
      
    @Autowired
    @Lazy
    private RemoteService remoting;
}
@DependsOnDuring component-scanning, it is used to specify the beans on which the current bean depends on. The specified beans are guaranteed to be created by the container before this bean.

public class SomeService {
      
    @Autowired
    @DependsOn ("pingService")
    private RemoteService remoting;
}
@LookupIndicates a method as ‘lookup’ method. It is best used for injecting a prototype-scoped bean into a singleton bean.

@Component
@Scope("prototype")
public class AppNotification {
    //prototype-scoped bean
}

@Component
public class NotificationService {
 
    @Lookup
    public AppNotification getNotification() {
        //return new AppNotification();
    }
}
@PrimaryIndicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency.

When not using @Primary, we may need to provide @Qualifier annotation to correctly inject the beans.

In given example, when FooRepository will be autowired, the instance of HibernateFooRepository will be injected – until @Qualifier annotation is used.

@Component
public class JdbcFooRepository 
	extends FooRepository {
}

@Primary
@Component
public class HibernateFooRepository 
	extends FooRepository {
}
@Scope Indicates the name of a scope to use for instances of the annotated type. In Spring 5, beans can be in one of six scopes i.e. singleton, prototype, request, session, application and websocket.

2. Context configuration annotations

These annotations helps in binding the different beans together to form the runtime application context.

AnnotationDescription
@ComponentScan@ComponentScan along with @Configuration is used to enable and configure component scanning. By default, if we do not specify the path, it scans the current package and all of its sub-packages for components.

Using component scanning, spring can auto-scan all classes annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository and configure them with BeanFactory.

@Configuration
@ComponentScan(basePackages = {com.howtodoinjava.data.jpa})
public class JpaConfig {
	
}
@ConfigurationIndicates that a class declares one or more @Bean methods and can be processed by the container to generate bean definitions when used along with @ComponentScan.

@Configuration
public class AppConfig {
	
	@Bean
	public AppUtils appUtils()
	{
		return new AppUnits();
	}
}
@ProfileIndicates that a component is eligible for bean registration when one or more specified profiles are active. A profile is a named logical grouping of beans e.g. dev, prod etc.

@Bean
@Profile("dev")
public AppUtils appUtils()
{
	return new DevAppUnits();
}

@Bean
@Profile("prod")
public AppUtils appUtils()
{
	return new ProdAppUnits();
}
@ImportIndicates one or more component classes to import — typically @Configuration classes. @Bean definitions declared in imported @Configuration classes should be accessed by using @Autowired injection.

@Configuration
@Import({ JpaConfig.class, SchedulerConfig.class })
public class AppConfig {

}
@ImportResourceIndicates one or more resources containing bean definitions to import. It is used for XML bean definitions just like @Import is used for java configuration using @Bean.

@Configuration  
@ImportResource( { "spring-context.xml" } )  
public class ConfigClass { 

}

Drop me your questions related to above provided spring annotations list or their explanation.

Happy Learning !!

Ref:

Context annotations package
Stereotype annotations package

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.