Saturday, September 25, 2021

Top 10 Spring Framework Annotations for Java Programmers | Example Tutorial

Hello guys, if you are learning the Spring framework and want to know what are essential Spring annotations you should know then you have come to the right place. Earlier, I have shared the free Core Spring and Spring Boot courses and Spring certification resources for Java developers, and in this article, you will find some of the most common annotations in this article, which is a must for a Java developer to work with Spring. You will also learn what does annotation really does and why should you learn them. There is no doubt that the Spring framework is one of the most popular Java frameworks, and it has made the life of Java developers easy by providing some excellent features in the last 15 years. 

Spring uses dependency injection to configure and bind your application together, but it doesn't force you to implement one of its interfaces. This allows you to code POJO (everyday old Java objects), a class with methods and attributes to do most of your stuff. 

Then the questions come, how does Spring provides those magical features if it doesn't ask you to implement their interface, well, they use annotations and many of them. 

I have been using Spring from Spring 2.0 when everything was configured using XML, I slowly moved to the annotation-driven configuration and then found my way towards Java-based configuration.

What this proves is that Spring is continuously evolving, and you have to keep up with its pace to keep yourself up-to-date, and knowing some essential Spring annotations will undoubtedly help in your journey of Spring.

If you have been coding Java for a couple of months, then you may have come across at least the annotations. The type which starts with "@" like @Override, possibly the most popular Java annotations ever. This helpful little metadata can do wonders in terms of improving code quality and reducing the chance of errors.

Ever since annotations were introduced in JDK 1.5, they have entirely changed the Java landscape with more and more frameworks adopting them to provide services and features, and Spring is no different.

They make heavy use of Annotations to provide features you love, like automatically detecting beans, creating their instances, and injecting them into the objects which need them. Btw, if you are new to Spring, then I suggest you check a comprehensive course like Spring Framework 5 Beginner to Guru, which will not only teach you these annotations but also other spring fundamentals you need to know to work effectively with Spring.




10+ Essential Spring Core Annotations for Java developers

Since annotations are providing the interface between Java and Spring, a Java developer needs to be familiar with the essential interface and understand what they do and how to use them. In this article, I'll share some of the critical Spring annotations, which I think a full-stack Java developer with Core Spring and Spring Boot experience should know.

1. @Configuration

This Spring annotation marks a class as a source of bean definitions, and it's one of the essential annotations if you are using Java-based configuration. In earlier days, I have used an XML file to declare bean, but now you don't need to do that; you can create classes and have methods that can return Spring bean. 

This means you don't need to look for XML File and you can use IDE's navigation feature to find out how your spring application is configured, including beans. 

here is the simplest example of @Configuration annotation to declare a configuration class using Java:

import org.springframework.context.annotation.*;

@Configuration
public class JavaConfig {
   @Bean 
   public SpringBean createSpringBean(){
      return new SpringBean();
   }
}

In this example, the method annotated with @Bean tells the Spring framework that they will return an object which should be registered as Spring bean. You can pass any class annotated with @Confguration to AnnotationConfigApplicatoinContext to load and access those beans in your application.  

You can also check a comprehensive spring course like Spring Framework Master Class - Java Spring the Modern Way by Ranga Karnam on Udemy to learn more about the modern ways to configure spring applications in Java. 


2. @ComponentScan

This Spring annotation instructs Spring to scan the package for all the @Configuration classes, which contains Spring bean definition in Java-based configuration.

10 Essential Spring Core Annotations Every Java Developer Should Learn


3. @Bean

This Spring core annotation indicates that a method produces a bean to be managed by the Spring container. This is commonly used in the classes which are annotated with @Configuration annotation on the Java-based configuration in Spring.

Here is an example of @Configuration and @Bean annotation in Spring which is similar to the earlier example we have seen above

@Configuration
public class BookStoreConfig {

  @Bean
  public BookStoreService bookStoreService() {
    return new BookStoreServiceImpl();
  }
}

In this example, we have annotated the BookStoreConfig class with @Configuration to indicate that it contains bean definitions. And, where are those bean definitions? Well, the methods are annotated with @Bean annotation. In this example, the bookStoreService() method returns a Spring bean.  You can also check Spring & Hibernate for Beginners (includes Spring Boot) for more examples.

Top 10 Spring Framework Annotations for Java Developers



4. @Component

This is another basic Spring annotation that can turn your class into a Spring bean at the auto-scan time. In general, not all the classes you create will be Spring bean in your project, but if a class depends upon another class and you want Spring to autowire that dependency, then you can annotate the class with @Component annotation.

One of the most famous examples of a @Component annotation is @Controller classes, which act as a Spring MVC controller and handles HTTP requests. They are automatically detected by Spring using annotation-based configuration and classpath scanning.

Again, this is a class-level annotation, and here is an example, inspired by my favorite Spring book, Spring in Action book by Craig Walls:

@Component
public class MangoShake implements Dessert{
  ..... 

}

Since this class is annotated with @Component, they will be picked up during component-scanning and created as a bean in the Spring application context. Then Spring can use that reference to autowire any dependency which is looking for a Dessert object.


5. @Service

Similar to @Controller annotation used in Spring MVC, @Service is also a specialization of the @Component annotation, which has no encapsulated state. You can further read my article, the difference between @Service and @Controller annotations in Spring, to learn more about it.


spring core annotations example



6. @Autowired

This Spring annotation instructs Spring’s dependency injection to wire an appropriate bean into the marked class member.

Here is another example from the classic Spring in Action book:

@Autowired
public void setDessert(Dessert sweet){
  this.dessert = sweet;
}

When Spring sees this method, it will try to find out a Spring bean with type Dessert and can call this method to inject the dependency.  See Spring Fundamentals By Bryan Hansen on Pluralsight for more examples of @Autowired annotation in Spring.

Core Spring Framework Annotations for Java Developers





7. @Lazy

This Spring framework annotation makes @Bean or @Component be initialized on demand rather than eagerly. I have not really used @Lazy annotation so often, if you have a good case or scenario where @Lazy annotation makes sense then feel free to share with us. 


8. @Qualifier

This annotation is used to filter what Spring beans should be used to @Autowire a field or parameter. You can use this annotation on a field or parameter as a qualifier for candidate beans when autowiring. It is mainly used to resolve the autowiring conflict when there are multiple beans of the same type.

Remember the Dessert and Cake example of Spring in Action, in which we have a setDessert() method which uses @Autowired for auto-wiring dependency.

Now, if we have more than one Dessert bean in the Spring application context, then Spring will confuse and not be able to inject any dependency. Instead, it will throw NoUniqueBeanDefinitionException.

You can resolve that ambiguity by using @Qualifier annotation, as shown below:

@AutoWired
@Qualifier("iceCream")
public void setDessert(Dessert dessert){
this.dessert = dessert;

}

This code will instruct Spring to inject the bean with id "iceCream" that should be injected into this method.



9. @Value

This Core spring annotation indicates a default value expression for the field or parameter, typically something like “#{systemProperties.myProp}”

Here are a couple of examples of @value annotation in spring:

@Value("NA")
private String name

This code injects the default String value into the property name, but instead of just plain string, you can also inject values from the property file and system properties. See Spring Framework 5 Beginner to Guru for more examples.

Top 10 Spring Framework Annotations for Java Developers



10. @Required annotation

This annotation can be used to specify a mandatory dependency. It can even fail the configuration if the dependency cannot be injected.

For example, you can annotate a method with @Required to indicate it's mandatory and required. If the setter method is not configured with a value, then the spring container will throw a BeanCreationException during the initialization phase of the bean. The required properties check happens before the container starts applying the property values to the bean.

Here is an example of @Required annotation in the Spring framework:

public class Profile{
 private String username;

 @Required
 public void setUsername(String username){
  this.username = username;

 } 

}
}

Here username property is required, and if setUsername() is not called or username is not set, the bean creation process will fail.


That's about some of the essential Spring framework annotations. As a Java spring developer, you should know about them and learn when to use them in your code. Though we have covered some of the basic and most important annotations, there are many more existing in the Spring framework. If you want even more, then I encourage you to look at Spring Framework Master Class, which covers the Spring framework in exquisite detail.


Other Java And Spring Articles you may like

Thanks for reading this article so far. If you like to find this list of Spring framework annotations useful, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are a Java developer who wants to learn Spring frameworks like Core Spring, Spring MVC, or Spring Boot and looking for some free courses to start with then you can also check out these free Spring Core, Spring MVC, and Spring Boot courses for Java developers to start with. It contains some free online courses to learn Spring from Udemy, Pluralsight, and other online learning platforms.


4 comments:

  1. What is the role of "@Lazy" annotation's description. Isn't laziness the entire point of IoC?

    ReplyDelete
  2. Hello @Anonymous, By default, Spring will create each and every bean at start up. @Lazy annotation defers that until a bean is requested the first time. The benefits is that it reduces start up time, but increases the time for the first request. You'd want to use it when you have an infrequently used part of your app and/or that is very slow to start up.

    ReplyDelete
  3. much needed information

    ReplyDelete

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