Spring boot annotations with Example

Spring boot annotations with examples

Spring Boot is a popular Java-based framework that lets you create the standalone, production-ready enterprise application that you can just run.

The Spring Boot framework provides many important features such as auto-configuration, opinionated starter POM and many more.

The Spring boot framework allows you to focus on solving your business problems rather than spending hours on doing configurations.

Auto-configuration is the feature provided by the spring boot framework that made configuration easier.

To enable auto-configuration and conditional bean initialization you can use a few important spring boot annotations.

In this tutorial, we will take a look at popular spring-boot annotations, and what they do?

Spring Boot Annotations

The first annotation that spring boot provides is @SpringBootApplication.

This is one of the most important annotations in spring boot because it bootstraps the application.

If you have gone through my spring boot hello world example, then you might have seen this annotation on top of the main application class.

This is the first annotation you will be using while writing the spring boot program.

Even if you are going to attend an interview for the spring boot role, then there is a high chance that you may face questions based on spring boot annotations.

Let’s begin with @SpringBootApplication annotation.

@SpringBootApplication

We already discussed that@SpringBootApplication annotation is one of the most powerful annotations given by the Spring Boot framework.

But what it does?

Basically, @SpringBootApplication initializes the spring boot framework.

But How?

The Spring boot application annotation does three major tasks internally:

  • @SpringBootApplication tells spring that the class is a configuration class, so that spring container can process that class automatically.
  • It enables the component scan so that spring can scan that package and its sub-packages to find components and beans.
  • It enables the autoconfiguration feature of spring boot.

Let’s create a demo to learn what is @SpringBootApplication annotation is and it’s internal implementation.

At first, go to Spring Initializr project (https://start.spring.io/) and create a sample project. In my case, I have created the spring-boot-application-annotation-demo project.

Now, look at the main class of the project. In my case it is SpringBootApplicationAnnotationDemoApplication.

The above class is annotated with the @SpringBootApplication annotation. If you look at the annotation definition then you will find that @SpringBootApplication annotation is equivalent of using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes.

@SprintBootApplication definition
@SprintBootApplication definition

Let’s take a look at all three annotations and what they do?

@Configuration

@Configuration annotation is a part of the spring core framework that tells spring container that the class may have bean definitions (@Bean).

Therefore, whenever the spring container sees a class with @Configuration annotation, the container assumes that the class is the source of bean definitions and it automatically processes that class at runtime.

But how the spring container knows where to find a configuration class?.

It’s simple.

@ComponentScan is one of the few core annotations of the spring framework that does this job.

@ComponentScan

@ComponentScan annotation tells spring container to look for configuration, component, service, and controller classes in a specified package.

If we provide package details along with @ComponentScan then spring will look for configuration and stereotype annotated classes only in that specified package. 

However, if no package specified then Spring will scan the current package and its sub-packages to scan for those classes.

The third annotation is @EnableAutoConfiguration that enables the most important feature of spring boot i.e Auto Configuration.

@EnableAutoConfiguration

As we all know that spring boot is an opinionated framework that follows the opinionated default configuration approach.

@EnableAutoConfiguration automatically configure the spring application based on included jars in project classpath.

Let’s understand this concept by an example. 

Suppose you have the h2 database in your classpath then you don’t have to configure data source manually.

 If your Application class or Main class is Annotated with @SpringBootApplication annotation (that uses @EnableAutoConfiguration)  then spring boot does all required configuration for you automatically without even writing a single line of code.

To put it differently, we can conclude that @SprintBootApplication initializes the Spring and Spring Boot framework.

Moreover, it enables the autoconfiguration feature of the spring boot framework.

Conditional Bean Initialization

Spring Boot provides a few annotations that enable the conditional bean initialization.

You can use those conditional annotations to define a condition under which certain bean should be initialized.

Let’s take a look at them one by one.

@ConditionalOnClass

Let’s try to understand the @ConditionalOnClass annotation with the help of an example.

ConditionalOnClass Spring Boot Annotation
ConditionalOnClass Spring Boot Annotation

As you can see SecurityAutoConfiguration class is annotated with the @ConditionalOnClass annotation.

But what does it mean by @ConditionalOnClass annotation?

Basically, @ConditionalOnClass annotation says that SecurityAutoConfiguration is available only if DefaultAuthenticationEventPublisher is available in the classpath.

Let’s take a look into one more example.

Spring Boot Annotation Example

Here, I have created one configuration file MyConfiguration and one class MyFramework

Now let’s create one more project and create a file MyService.java.

Forthwith create and export a jar file (MyService.jar) of this project using File->Export.

Now go to the spring-boot-application-annotation-demo project and take a look at the SpringBootApplicationAnnotationDemoApplication, MyConfiguration file.

In the above example, it is clear that spring container will initialize MyFramework only if MyService class is present in our classpath.

Let’s verify the output in both the scenarios when MyService is available in the classpath and when not.

Scenario -1 : MyService is available in the classpath.

There is no error, and the program is producing the result as expected.

Scenario 02: When MyService is NOT present in the classpath.

Spring Boot Annotation Example

The above program will throw a run time error saying that spring container can’t find the bean of type MyFramework.

Field framework in com.codedelay.springbootapplicationannotationdemo.SpringBootApplicationAnnotationDemoApplication required a bean of type 'com.codedelay.springbootapplicationannotationdemo.MyFramework' that could not be found.

From the above two programs, it is clear that if the ConditionalOnClass annotation is used then it will configure the bean only if the dependency class is available in the classpath.

@ConditionalOnMissingClass

Let’s understand the ConditionalOnMissingClass concept using the below example.

ConditionalOnMissingClass annotation example

Create two bean classes MyFramework and MyService.

Inside MyConfiguration class add the below code.

In the above example, you could see that myService() bean definition is annotated with ConditionalOnMissingClass annotation.

That means spring container will process myService only if MyFramework class is not present in the classpath.

@ConditionalOnBean

ConditionalOnBean is another important annotation for conditional bean creation in spring boot.

When this annotation is placed on a @Bean, then spring container will initialize bean only if specified bean or class is present in the container.

Let’s understand this concept by an example.

In the above example, you could see that two bean definitions are present under myFramework() and myService().

But myService() is annotated with ConditionalOnBean.

So, myService() will be processed by spring container only if it finds myFramework bean in the container.

If it is not then it will not initialize MyService bean.

@ConditionalOnMissingBean

ConditionalOnMissingBean is similar to the ConditionalOnMissing class. The only difference is that when bean definition is annotated with ConditionalOnMissing class annotation then spring container will initialize bean only if specified bean name is not initialized by the spring container.

@ConditionalOnProperty

ConditionalOnProperty in another @Conditional variant that tells spring container to initialize bean based on properties value defined in property file (eg. application.properties)

In the above example, myFramework() is annotated with @ConditionalOnProperty. Therefore, spring container will initialize the bean only if the enabled property is present in application.properties and its value is zero.

@ConditionalOnJava

As the name suggest, ConditionalOnJava allows spring container to initialize bean only if java version condition match. In the above example, the spring container will process myService only if the java version is older than 1.8. 

Let’s look into one more example where we will initialize been conditional. I mean to say we will initialize myNewService bean when Java version is Eight and above and we will initialize myOlderService bean when in Java version is older than Eight.

Let’s look into one more way to initialise been conditionally.

Suppose you want to initialize bean only if some configuration file is present in the filesystem or in the environment then and you can use @ConditionalOnResource.

From the above example, it is clear that spring container will initialize myNewService bean only if the resource file app.txt  is present in the filesystem.

Conclusion

I hope now you get some understanding of spring boot annotations.

If you have any doubts about spring boot or you need any information, you can ask your doubts in the comments section.

2 thoughts on “Spring boot annotations with Example”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.