Spring Core Annotations

By | | Updated : 2021-05-29 | Viewed : 60 times

Spring Core Annotations

As a spring developer, it is required to know all the spring core annotations. I tried to bring all the spring core annotation in one article. I hope these will be useful for every spring developer.

Spring DI Annotations

@Bean

@Bean is a method-level annotation that is used to declare Spring bean. It must be used within the @Configuration class only for declaring the single spring bean explicitly.

With the annotated @Bean method, the bean will be initiated and initialized by a spring container. It does work the same as element in spring-beans.xml.

ASpringBean.java
@Bean
    public ASpringBean aSpringBean() {
        return new ASpringBean("ASpringBean");
    }

@Bean vs @Component

  • @Bean is method-level annotation whereas @Comoponent is a class-level annotation.

  • @Component annotation will be preferred for bean's auto-detection by using classpath scanning whereas @Bean annotation is certainly used for declaring the single bean explicitly.

  • Unlike @Component, @Bean should be declared in the @Configuraton class. Bean instance logic can be controlled with @Bean whereas it is not possible with @Component.

  • Unlike @Component, @Bean annotation does not allow to wire the dependencies dynamically So dependencies injection should explicitly happen in the case of @Bean.

@Autowired

@Autowired indicates that annotated constructor, setter, or filed to be injected/wired as a dependency into other beans. Generally speaking, dependency injection will happen by @Autowired annotation automatically by the Spring container.

Spring inject mandatory beans when annotated @Autowired (required = true). The default value of @Autowired is false.

ASpringBean.java
@Component
public class ASpringBean {

    private String aSpringBeanName;

    @Autowired
    private BSpringBean bSpringBean;

	//other methods

}

@Qualifier

@Qualifier annotation must be used with @AutoWired. It should be used when spring faces ambiguity of bean\'s type in autowiring. So here spring throws the exception called NoUniqueBeanDefinitionException. It is required to use here @Qualifier to auto-wire the beans by Spring. @Qualifier annotation must be used like @Qualifier ("nameOfSpringbean") then spring\'s job will be easy in autowiring.

ASpringBean.java
@Component
public class ASpringBean {

    private String aSpringBeanName;

    @Autowired
    @Qualifier("bSpringBean")
    private BSpringBean bSpringBean;

	//other methods

}

@Required

@Required is applicable only for setter methods for verifying the property/bean\'s availability at the time of configuration. Here early initiation of bean will happen by spring container. To enable the @Required annotation, RequiredAnnotationBeanPostProcessor must be registered. All the @Required bean\'s availability will be checking by RequiredAnnotationBeanPostProcessor. Note: It is deprecated from Spring framework 5.1.

@Value

Typically used for @Value for injecting the external properties as like properties.

CarService.java
@Service
public class CarService {
       
    @Value("${car.brand}")
    private String carBrand
}

@DependsOn

It defines the bean on which the current bean depends. This means it describes the bean which is to be created first. So once this bean initiation happens then the current bean\'s initiation is next.

Car.java
@Component
public class Car {
       
    @Autowired
    @DependsOn ("engine")
    private Engine engine;
}

@Primary

Spring will give priority to annotated beans When there are multiple beans of the same type for autowiring. So priority will be given to @Primay annotated bean for autowiring.

@Primary example
@Component
public class Audi extends Car {
}
 
@Primary
@Component
public class Benz extends Car {
}

@Scope

Spring recognizes bean scope when encountering this @Scope annotation in the initiation of bean. Spring beans scopes such as singleton, prototype, etc can be defined using with @Scope annotation.

@Scope example
@Bean
@Scope("singleton")
public Person aSpringBean() {
    return new ASpringBean();
}

Context Configuration Annotations

@Profile

@Profile annotation allows spring to crate the component based on the activated profiles. Suppose When we have a scenario like different Beans creation is required to happen based on the environment then @Profile is the only option.

AppConfig.java
@Configuration
public class AppConfig 
{
 	@Bean
 	@Profile("DEV")
	 public DataSource devDataSource() {
	
	}
}

@Import

Indicate that other config classes can also be imported into the current configuration class. Means other component\'s configurations can be used in the current configuration class.

AppMainConfig.java
@Import(AppConfig.class) 
public class AppMainConfig { 
 	//other annoatated configuration 
}

@ImportResource

Indicate that other config-bean.xml can be imported into the current configuration classes.

AppMainConfig.java
@Configuration 
@ImportResource( { "spring-beans.xml" } ) 
public class AppMainConfig { 
 	//other annoatated configuration 
}

@PropertySource

Using this annotation defined property file can be used in the current config class.

AppMainConfig.java
@Configuration 
@PropertySource("classpath:/mainapp.properties") 
public class AppMainConfig {
}

@PropertySources

using this annotation multiple defined property files can be used in the current config class.

AppMainConfig.java
@Configuration @PropertySources({ 
@PropertySource("classpath:/mainapp1.properties"), 
@PropertySource("classpath:/mainapp2.properties") }) 
public class AppMainConfig {}

@Lookup

Lookup method injection is used to override spring bean definition so that spring will create bean based on Lookup method definition. Spring can not handle a scenario like when a prototype scoped bean injection into singleton scoped bean injection. As you know dependency injection will happen only once for singleton scoped beans. So prototyped scoped bean will be created only once which is Here it is required to create the bean for a prototype for each and every time.

ASpringBean.java
@Component
public class ASpringBean {

    @Lookup
    public BSpringBean bSpringBean() {
        return null;
    }
}

@Lazy

Conceptually all @Bean methods in the @Configuration class initialized eagerly which means at the time of bootstrapping to avoid all the errors. But when encounter the @Lazy in the @Configuration class then initialization of those beans will happen lazily.

SpringAppConfig.java
@Lazy
@Configuration
public class SpringAppConfig {

    @Bean
    public ASpringBean aSpringBean() {
        return new ASpringBean("ASpringBean", bSpringBean());
    }

    @Bean
    public BSpringBean bSpringBean() {
        return new BSpringBean("BSpringBean");
    }

}

Please refer to the Docsconsole GitHub repo for examples.

Leave A Reply