Top 5 Spring Boot Annotations with Examples for Java Developers

Annotations have completely changed the way you write Java code. It's now impossible to write any Java code without using annotations but that's for good. They provide a lot of value and that's why it's important for a Java developer to get familiar with essential annotations of the framework he or she is using. When I think about Java, some of the essential annotations which come in our mind is @Override, @SuppressWarning and @Deprecated. Similarly, if you are using Spring Boot framework, an extension of Spring framework which aims to simplify the Java development with Spring, you will often end of using a couple of annotations like @SpringBootApplication or @EnableAutoConfiguration.

Many Java developer just blindly uses annotations without knowing that what they are and what they do. They just copy paste the code without giving much thought.

For example, the @SpringBootApplication annotation is required to most of the main class you write with Spring Boot, hence, most of the Java developer end up just copy-pasting whole class and they trying to customize it for their own need.

Well, nothing is bad, as long as you know what you are doing but just learning a bit of fundamental never hurt. Even small information that what does the particularly annotation do and when to use them will go a long way in improving your understanding of the code you write or read.

In order to bridge this gap, I am going to share some of the essential Spring Boot annotations every Java developer should be familiar with. I'll just provide a quick overview with an example for the sake to keep this article short but you join Learn Spring Boot in 100 Steps to learn them in depth with more real-world examples.




Spring Boot Annotations Java Developer should know

Without wasting any more of your time, here is my list of some of the useful Spring Boot annotations which every Java developer using Spring Boot should be familiar with.

1.@SpringBootApplication

This is the most common Spring Boot annotations and you will find it probably in every single Spring Boot application. Since Spring Boot allows you to execute your Web application without deploying into any web server like Tomcat.

You can run them just like you can run the main class in Java, this annotation is used to annotate the main class of your Spring Boot application. It also enables the auto-configuration feature of Spring Boot.

Here is an example of using the @SpringBootApplication in Java:

package boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
public class SpringBootDemo {

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

}

@RestController
class HelloControler{ 

@RequestMapping("/")
public String hello(){
  return "Hello Spring Booot";
}

}

This is the simplest example of RESTful web service you can write using Spring and Java. You can run this like any Java application by right-clicking on the source file and "Run as Java application" in Eclipse. After that, embedded Tomcat server will start and deploy this RESTful web service.

When you will hit the URL http://localhost:8080/ (the default port for embedded tomcat server inside Spring boot) you will be greeted with "Hello Spring Boot".

Now, coming back to the @SpringBootApplication annotation, it's actually a combination of three annotations - @Configuration, @ComponentScan, and @EnableAutoConfiguration.

If you know the @Configuration enables Java-based configuration and the class annotated with @Configuration can be used to define Spring Beans.

The @ComponentScan enables component scanning so that controller or any other component class you create will be automatically discovered and registered with Spring Bean.

And, finally, the @EnableAutoConfiguration enables the auto-configuration feature of Spring Boot which can automatically configure certain Spring features based upon JAR available in Classpath. For example, if H2.jar is present in the classpath, it can configure the H2 in-memory database inside the Spring application context.

As explained by Dan Vega on his Spring Boot MasterClass, Spring Boot makes more than 200+ decision to free you from common configuration task. If you want to customize those decisions you can do so.

Top 5 Spring Boot Annotations Java Developers Should Know


Btw, the @SpringBootApplication annotation is only available form Spring Boot version 1.1, It wasn't part of Spring Boot's first release and later added because they realize that almost all the applications were annotated with those three annotations (@Configuration + @ComponentScan, and @EnableAutoConfiguration).



2.@EnableAutoConfiguration

This is the original Spring Boot annotation which was added to enable the auto-configuration, the flagship Spring boot feature which frees developers from common configuration task.

The auto-configuration feature automatically configures things if certain classes are present in the Classpath e.g. if thymeleaf.jar is present in the Classpath then it can automatically configure Thymeleaf TemplateResolver and ViewResolver.

If you are not using @SpringBootApplication or running on Spring boot version lower than 1.1 then you can use @EnableAutoConfiguration annotates to enable the auto-configuration feature of Spring Boot.


Another thing which is worth knowing about @EnableAutoConfiguration is that it allows you to selectively ignore certain classes from auto-configuration using exclude attribute as shown below:

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class SpringBootDemo {
  //.. Java code
}

If the class is not on the classpath, you can use the excludeName attribute of the @EnableAutoConfiguration annotation and specify the fully qualified class name, as explained by Ranga Karnan on  Learn Spring Boot in 100 Steps course. One of the best course for beginners to learn Spring boot.

@EnableAutoConfiguration Spring Boot annotation example


Btw, this Spring Boot annotation is really useful for experienced Spring Boot programmers who think that Spring boot is too opinionated and want to have some control over the auto-configuration feature.



3.@ContextConfiguration

This annotation specifies how to load the application context while writing a unit test for Spring environment. Here is an example of using @ContextConfiguration along with @RunWith annotation of JUnit to test a Service class in Spring Boot.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=PaymentConfiguration.class)
public class PaymentServiceTests{

@Autowired
private PaymentService paymentService;

@Test
public void testPaymentService(){

  // code to test PaymentService class

}

}

In this example, @ContextConfiguration class instructs to load the Spring application context defined in the PaymentConfiguration class.

Btw, even though it does a great job of loading Spring application context, it doesn't provide full Spring boot treatment.

As explained by Craig Walls in Spring Boot in Action, the Spring Boot applications are ultimately loaded by SpringBootApplicaiton either explicitly or using the SpringBootServletInitializer.


@ContextConfiguration Spring Boot annotation example


This not only leads beans in Spring application context but also enables logging and loading of properties from external property file like applicaiton.properties as well as other Spring Boot features. But, don't worry, there is another annotation which provides all of this and you can use that to write a unit test with Spring boot treatment.



4.@SpringApplicationConfiguration

This is the annotation which addresses shortcomings of @ContextConfiguration annotation discussed in the previous section. It provides full Spring Boot treatment to your test classes e.g. it not only load the beans in Spring application context but also enable logging and loads properties from application.properties file.

Btw, you should always use @SpringApplicaitonConfiguration instead of @ContextConfigruation for writing unit test in Spring boot.

Here is an example of using @SpringApplicatoinConfiguration annotation in Spring boot:


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=PaymentConfiguration.class)
public class PaymentServiceTests{
  ...

}

This is the same example we have seen in the last section but re-written using the @SpringApplicationConfiguration annotation this time. Again, I suggest you check out the Spring Boot in Action book to learn more about it, one of the best books to learn Spring Boot framework.




5.@ConditionalOnBean

Spring Boot defines several conditional annotations for auto-configurations e.g. @ConditionalOnBean which can be used to apply a configuration if the specified bean has been configured.


5.1 @ConditionalOnMissingBean
Similarly, you have @ConditionalOnMissingBean, which enables the configuration if the specified bean has not already been configured.

@ConditionalOnClass
Configuration is applied if the specified class is available on the Classpath.


5.2 @ConditioanlOnMissingClass
This is the counterpart of the previous annotation. This configuration is applied if the specified class is not present on the Classpath.


5.3 @ConditionalOnExpression
The Configuration is applied if the given Spring Expression Language (SpEL) expression evaluates to true.


5.4 @ConditionalOnJava
The Configuration is applied if the version of Java matches a specific value or range of versions.

Apart from these conditional annotations listed here, there are more e.g. @ConditioalOnJndi, @ConditioanlOnProperty, @ConditioanlOnResource, @ConditionalOnWebApplication, and @ConditionalOnNotWebApplication which works depending upon the presence and absence of some conditions.

If you are interested to learn more about them, I suggest to go through Spring Framework 5: Beginner to Guru, one of the best course to learn Conditionals and Spring Boot annotations.



That's all about some of the essential Spring Boot annotations every Java developer should know. If you are using Spring Boot for creating Spring-based Java web application then you will come across these annotations every now and then. Just knowing what they do and where you can use will give you confidence while reading and writing Spring boot code.

Further Learning
Learn Spring Boot
Master Java Web Services with Spring Boot
Master Hibernate and JPA with Spring Boot in 100 Steps


Other Java and Spring articles you may like
5 Spring Boot Features Every Java Developer Should Know (features)
Top 5 Free Courses to learn Spring and Spring Boot in 2019 (courses)
5 Course to Master Spring Boot online in 2019 (courses)
10 Things Java Developer should learn in 2019 (goals)
10 Tools Java Developers use in their day-to-day life (tools)
10 Tips to become a better Java developer in 2019 (tips)
3 Best Practices Java Programmers can learn from Spring (best practices)
5 courses to learn Spring Boot and Spring Cloud in 2019( courses)

Thanks for reading this article so far. If you find these Spring Boot annotations useful then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

No comments:

Post a Comment