Spring Boot Annotations

Spring Boot Annotations

In this article, We will learn various annotations used in Spring Boot.

If you have not read my introduction article of Spring Boot, I would request you to take a look –  Spring Boot Tutorial.

Annotations in Spring Boot are mostly available in below packages :

  • org.springframework.boot.autoconfigure
  • org.springframework.boot.autoconfigure.condition

Let’s get started :

1) @SpringBootApplication

Spring Boot’s most important feature is it’s auto-configuration. Auto-configuration in Spring Boot is done by scanning the components, which means it scans all the classes with @Component annotation.  It also scans the classes for @Configuration annotation to initialize extra beans.

@SpringBootApplication annotation enables the application to do all these things.

Java class , which is annotated with @SpringBootApplication annotation, is considered as main class of Spring Boot and the application starts from this class.

So we can say that addition of @SpringBootApplication annotation is equivalent to using @Configuration, @ComponentScan and @EnableAutoConfiguration annotations with their defaults.

Spring Boot Annotations

That means, @SpringBootApplication enables below mentioned features :

  1. @SpringBootConfiguration Annotation : Used to register the extra beans.
  2. @ComponentScan Annotation : Used to enable the Component scanning.
  3. @EnableAutoConfiguration Annotation : Used to enable the auto-configuration feature.

Example of @SpringBootApplication annotation

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

public static void main(String[] args) {
SpringApplication.run(App.class, args);
}

}

2) @EnableAutoConfiguration

@EnableAutoConfiguration enables the Spring Boot application’s auto-configuration feature. Which means Spring Boot will look for all the auto-configuration beans on its classpath and it automatically applies them.

Suppose, if we have a jar tomcat-embedded.jar on classpath of our Application then it will automatically configure the TomcatServletWebServerFactory class.

@EnableAutoConfiguration gets used with the @Configuration annotation.

As we learnt earlier, @EnableAutoConfiguration is automatically included with @SpringBootApplication so if we add it again on main class then it will not have any impact.

It is advised that @EnableAutoConfiguration should be only used once.

Spring Boot locates the auto-configuration classes using the SpringFactoriesLoader mechanism.

Example of @EnableAutoConfiguration annotation

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class App {

public static void main(String[] args) {

SpringApplication.run(App.class, args);

}
}

3) @SpringBootConfiguration

Classes , which provides the Spring Boot Application configurations, are annotated with @SpringBootConfiguration annotation. Thus, this annotation tell Spring Boot that this class has configuration for the application.

As , @Configuration annotation of Spring is also used for annotating class as configuration classes so @SpringBootConfiguration is considered as alternative option of @Configuration annotation.

Spring Boot Application should only have one class annotated with @SpringBootConfiguration and Spring Boot applications will inherit it from @SpringBootApplication.

However, there is a difference between both these annotations :

@SpringBootConfiguration annotation has feature that it allows configurations to be located automatically but @Configuration doesn’t have this feature.

@SpringBootConfiguration annotation is very useful for unit and integration tests.

Example of @SpringBootConfiguration annotation

@SpringBootConfiguration
public class App {

public static void main(String[] args) {
SpringApplication.run(App.class, args);
}

@Bean
public EmployeeService employeeService() {
return new EmployeeServiceImpl();
}
}

4) @ImportAutoConfiguration

@ImportAutoConfiguration annotation is Spring Boot is used to import and apply the specified auto-configuration classes.

@EnableAutoConfiguration and @ImportAutoConfiguration annotation provides somehow similar features but there exists one difference :

The difference between @ImportAutoConfiguration and

  • @EnableAutoConfiguration annotation configure all beans that are found in the application’s classpath at the time of Scanning.
  • @ImportAutoConfiguration only consider those configuration classes which are provided in the annotation.

@ImportAutoConfiguration is used when we do not require to enable the default auto-configuration.

Example of @ImportAutoConfiguration annotation

// In below example, com.techblogstation.controllers is path where my controller classes exists
@ComponentScan("com.techblogstation.controllers")
@ImportAutoConfiguration({WebMvcAutoConfiguration.class
    ,DispatcherServletAutoConfiguration.class
    ,EmbeddedServletContainerAutoConfiguration.class
    ,ServerPropertiesAutoConfiguration.class
    ,HttpMessageConvertersAutoConfiguration.class})
public class MainApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(MainApplication.class, args);
    }
}

5) @AutoConfigureOrder, @AutoConfigureBefore and @AutoConfigureAfter

We have learnt above that How to apply the configurations to the Spring Boot Application.

Now if we want our configurations to be applied in one specific order then these annotations are used :

  • @AutoConfigureOrder
  • @AutoConfigureBefore
  • @AutoConfigureAfter

@AutoConfigureOrder annotation is used to order the certain auto-configuration classes which do not have any direct knowledge of each other.

@AutoConfigureBefore annotation is used when you want to apply your configuration but before the specific configuration is applied.

@AutoConfigureAfter annotation is used when you want to apply your configuration only after the specified configuration is applied.

Suppose, In your class you are providing web specific configurations then you may want that your configuration is applied after the WebMvcAutoConfiguration then this annotation is used.

6) Condition Annotations

In Spring Boot, It is possible that we can define the conditions to register the bean. Those beans will only gets register when the condition meets.

Auto-configuration classes in Spring Boot can have one or more @Conditional annotations.

Let’s understand the different conditional annotations in Spring Boot :

@ConditionalOnBean and @ConditionalOnMissingBean

@ConditionalOnBean and @ConditionalOnMissingBean annotations works on basis of presence or absence of specified bean.

  • It has a value attribute and this attribute specifies the type or name of the bean.
  • It has one search attribute and this attribute allows us to limit the hierarchy of ApplicationContext which is considered when searching for beans.

If the specified condition does not match then it restricts the configuration class to be registered.

Example of @ConditionalOnBean and @ConditionalOnMissingBean

@Bean("authService")
@Autowired

@ConditionalOnMissingBean(B2CAuthenticationService.class)

@ConditionalOnBean(
  value = 
{B2CProperties.class, SignUpPolicy.class, SignInPolicy.class, SignUpOrSignInPolicy.class, 
ResetPasswordPolicy.class, EditProfilePolicy.class, SignOutPolicy.class, NonceProperties.class, 
NonceService.class})

public B2CAuthenticationService authService(
  final ClaimValidationService claimValidationService,
  final NonceService nonceService,
  final UrlService urlService,
  final RestTemplate restTemplate){

    return new SimpleB2CAuthenticationService(
      claimValidationService,
      nonceService,
      urlService,
      restTemplate);
}

In the above example , the specified bean B2CAuthenticationService will only get registered  :

  • if a bean of type B2CAuthenticationService is not already defined in the application context.
  • and if beans defined in the @ConditionalOnBean are already registered.

@ConditionalOnClass and @ConditionalOnMissingClass

@ConditionalOnClass and @ConditionalOnMissingClass annotations allows the configurations to be loaded on the basis of presence or absence of specified classes

Spring ASM module is used to parse the metadata of annotations so even if the class is not present in runtime, we can always mention that class in our condition.

These annotations has value and name attribute to refer the real class or name respectively.

Example of @ConditionalOnClass and @ConditionalOnMissingClass

@Configuration
@ConditionalOnClass(EmbeddedAcmeService.class)
static class EmbedConfig
{

@Bean
@ConditionalOnMissingBean
public EmbeddedAcmeService embeddedAcmeService() { // The code / logic }

}

@ConditionalOnNotWebApplication and @ConditionalOnWebApplication

@ConditionalOnNotWebApplication and @ConditionalOnWebApplication annotations allows the configurations to be loaded on the basis of whether the application is a Web Application or Not.

Web Application in Spring Boot should meet one or more below mentioned requirements :

  • Web Application uses a Spring WebApplicationContext.
  • Web Application defines a session scope.
  • Web Application has a StandardServletEnvironment.

@ConditionalOnProperty

@ConditionalOnProperty annotation allows the configuration to be loaded only on the basis of presence and the value of a Spring Environment property.

This annotation can be used if we have different definitions of data sources for different environments.

Example of @ConditionalOnProperty

@Bean
@ConditionalOnProperty(name = "env", havingValue = "prod")
DataSource dataSource()
{
// The code / logic
}

@Bean
@ConditionalOnProperty(name = "env", havingValue = "dev")
DataSource dataSource()
{
// The code / logic
}

@ConditionalOnResource

@ConditionalOnResource annotation allows the configuration to be loaded only when the specified resource is present in the classpath. Resources in this condition is represented by using the usual Spring conventions.

Example of @ConditionalOnResource

@ConditionalOnResource(resources = "classpath:env.properties")
Properties properties()
{
// The code / logic
}

@ConditionalOnExpression

@ConditionalOnExpression annotation allows the configuration to be loaded on the basis of result of the specified expression. These expressions are also known as Spring Expression Language (SpEL).

This annotation is basically used when the condition is complex to evaluate.

Example of @ConditionalOnExpression

@Bean @ConditionalOnExpression("${env} && ${havingValue == 'dev'}") DataSource dataSource() {    // The code / logic }

@ConditionalOnCloudPlatform

@ConditionalOnCloudPlatform annotation allows the configuration to be loaded only when the specified cloud platform is active.

Example of @ConditionalOnCloudPlatform

@Configuration
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
public class ConditionExample
{
@Bean
public AppBean appBean(MyProp properties)
{
return new AppBean(properties.getName);
}
}

Conclusion

That’s all folks! In this article,  we have learnt all the basic and advance annotations used in Spring Boot and their examples.

Leave a Reply

Your email address will not be published. Required fields are marked *