Top 10 Spring Framework Annotations for Java Developers

There is no doubt that Spring framework is one of the most popular Java frameworks and it has made the life of Java developer easy by providing some awesome 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 (plain old Java objects), a class with methods and attributes to do most of your stuff. Then the questions come, how do Spring provides those magical features if it doesn't ask you to implement their interface, well they use annotations and many of them. You will find some of the most common annotations in this article, which is must for a Java developer to work with Spring.

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 constantly evolving and you have to keep up with its pace to keep yourself up-to-date and knowing some essential Spring annotations will certainly 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 of the annotations. The type which starts with "@" like @Override, possibly the most popular Java annotations ever. This nice 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 completely changed the Java landscape with more and more framework adopting them to provide services and features and Spring is no different.

They make heavy use of Annotations to provide features you love e.g. automatically detecting beans, creating their instances and injecting them to the objects who 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.



Spring Core Annotations for Java developers

Since annotations are providing the interface between Java and Spring, it's important for a Java developer 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 essential Spring annotations which I think a Java Spring developers should know.


@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, we use an XML file to declare bean but now you don't need to do that, you can create classes and have methods which can return Spring bean.


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


@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 inspired by Spring Framework Master Class course on Udemy:

@Configuration
public class BookStoreConfig {

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

In this example, we have annotated BookStoreConfig class with @Configuration to indicate that it contains bean definitions. And, where are those bean definitions? Well, the methods which are annotated with @Bean annotation. In this example, the bookStoreService() method return a Spring bean.  You can also check Spring Framework 5 Beginner to Guru for more examples.

Top 10 Spring Framework Annotations for Java Developers



@Component
This is another basic Spring annotation which can turn your class into a Spring bean at the auto-scan time. In general, not all the class 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 popular examples of a @Component annotation is @Controller classes which act 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 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.


@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, difference between @Service and @Controller annotations in Spring to learn more about it.


spring core annotations example



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

Here is another example from classic Spring in Action book:

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

When Spring will see 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

Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually. I have one and I also suggest all developers have that plan because Pluralsight is like NetFlix for Software developers.

It has more than 5000+ good quality courses on all latest topics. Since we programmers have to learn new things every day, an investment of $299 USD is not bad.

Btw, it also offers a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch this course for free by signing for that trial.



@Lazy
This Spring framework annotation makes @Bean or @Component be initialized on demand rather than eagerly.


@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 Spring application context then Spring will confuse and not 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" should be injected into this method.



@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 default String value to property name, but instead of a 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



@Required
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 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 on to the bean

Here is an example of @Required annotation in 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 exists in Spring framework and if you want even more then I encourage you to look at Spring Framework Master Class which covers Spring framework in fine details.


Further Learning
Master Microservices with Spring Boot and Spring Cloud
Master Hibernate and JPA with Spring Boot in 100 Steps
5 Free Spring Framework and Spring Boot Courses
15 Spring Boot Interview Questions with Answers
20 Spring MVC Interview Questions for Java Programmers
20 REST with Spring Interview Questions for Web developers
3 ways to learn Core Spring or Spring MVC better
6 Courses to learn Spring Framework Better


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

2 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