Sunday, May 21, 2023

5 Essential Spring Boot Annotations with Examples in Java - Tutorial

Hello guys, if you are coding in Java for long then you know that 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 to our mind are @Override, @SuppressWarning, and @Deprecated. Similarly, if you are using the Spring Boot framework, an extension of the Spring framework which aims to simplify the Java development with Spring, you will often end up 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 for most of the main class you write with Spring Boot, hence, most of the Java developers end up just copy-pasting the whole class and 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 fundamentals never hurt. Even small information that what does the particular annotation does 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 course to learn them in depth with more real-world examples.





5 Spring Boot Annotations Every 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 annotation and you will find it probably in every single Spring Boot application. Since Spring Boot allows you to execute your Web application without deploying it 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 a 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, the 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 in his Spring Boot MasterClass, Spring Boot makes more than 200+ decisions to free you from common configuration tasks. If you want to customize those decisions you can do so.

Top 5 Spring Boot Annotations with Examples for Java Developers


Btw, the @SpringBootApplication annotation is only available from Spring Boot version 1.1, It wasn't part of Spring Boot's first release and was 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 tasks.

The auto-configuration feature automatically configures things if certain classes are present in the Classpath like 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 that is worth knowing about @EnableAutoConfiguration is that it allows you to selectively ignore certain classes from auto-configuration using the 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 courses 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 the 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 the 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 the Spring application context but also enables logging and loading of properties from external property files like applicaiton.properties as well as other Spring Boot features. But, don't worry, there is another annotation that provides all of this and you can use that to write a unit test with Spring boot treatment.



4.@SpringApplicationConfiguration

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

Btw, you should always use @SpringApplicaitonConfiguration instead of @ContextConfigruation for writing unit tests 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 the Spring Boot framework.





5.@ConditionalOnBean

Spring Boot defines several conditional annotations for auto-configuration like @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
The 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 going through Spring Framework 5: Beginner to Guru, one of the best courses to learn Conditionals and Spring Boot annotations.

common Spring Boot annotations for Java programmers


That's all about some of the essential Spring Boot annotations every Java developer should know. If you are using Spring Boot for creating a 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.



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 (courses)
  • 5 Course to Master Spring Boot online (courses)
  • 10 Courses to learn Spring Security with OAuth 2 (courses)
  • 10 Things Java Developer should learn (goals)
  • Top 5 Books and Courses to learn RESTful Web Service (books)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 10 Tips to become a better Java developer (tips)
  • Top 5 Courses to learn Microservices in Java? (courses)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)
  • 5 courses to learn Spring Boot and Spring Cloud ( courses)
  • 3 ways to change Tomcat port in Spring Boot (tutorial)
  • 10 Advanced Spring Boot Courses for Java Programmers (courses)
  • 10 Spring MVC annotations Java developers should learn (annotations)
  • 10 Best Spring Courses for Senior Java developers (best courses)
  • 15 Spring Boot Interview Questions for Java Programmers (questions)

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

P. S. - If you want to learn Spring Boot in-depth but looking for some free resources to start with then I also recommend you check out this list of 10 Free Spring Boot tutorials and courses on Medium. This list contains some of the best free courses to learn Spring Boot from Udemy, Pluralsight, Coursera, and other online platforms.

2 comments:

  1. Do I need to remember these Spring boot annotations for interviews?

    ReplyDelete
    Replies
    1. If you have worked in Spring Boot then you will most likely remember these annotations but if you haven't then yes you should remember these annotation for interview purpose.

      Delete

Feel free to comment, ask questions if you have any doubt.