Introduction to Spring Framework Annotations
[thrive_toggles_group”][thrive_toggles title=”Read other articles of the series :” no=”1/1″]
- Spring Framework Annotations [Current Article]
- Spring MVC Annotations
- Spring Boot Annotations
[/thrive_toggles][/thrive_toggles_group]
In this post, we will get a quick introduction to Spring Framework Annotations. We will explore different annotations along with a few of the internal details for these Spring Framework Annotations.
Introduction
Java 5.0 introduced support for the annotations and quickly it became one of the preferred ways, Spring Framework was quick to adopt this and with 2.5 Spring Framework started support for annotations.
Though we can still use XML
based configurations to control/manage our Spring application, Spring Framework Annotations are now becoming a de facto standard for Spring-based enterprise applications.
1. Spring Core Annotation
In this section, we will cover Spring Framework Core Annotations.
1.1 @Required
@Required
annotation applied to the bean setter method to enforce require property. It can be used when we want to make sure that a specific bean is required to be injected by Spring, in case required Spring bean cannot inject the required bean, BeanInitializationException
is thrown.
@Required
public void setClient(OkHttpClient client) {
this.client = client;
}
1.2 @Autowired
@Autowired annotation used to inject object implicitly, We can apply this annotation to fields, setter methods, and constructors.
You can use @Autowired
annotation on the constructor, Spring will inject dependency at the time of object creation. Please note that you can only use this annotation to the maximum of 1 constructor for a class.
@Autowired
public WebConfiguration(RequestResult result){
this.requestResult=result
}
For @Autowire
annotation, Spring does not have the requirement for the constructor to be public.
We can also use @Autowire
annotation on the class property
@Autowired
private OkHttpClient client;
@Autowired
private ObjectMapper jacksonObjectMapper;
The third option is to use this annotation on the setter method, Spring internally will try to perform injection by Type.
@Autowired public void setClient(OkHttpClient client) { this.client = client; }
With Spring 4.3, @Autowire
has become optional on classes with a single constructor, so for the below code, Spring will try to inject an instance of the Customer (even we do not have @Autowire
annotation)
@Component
public class Customer {
private Order order;
public Customer(Order order) {
this.order = order;
}
}
1.3 @Qualifier
When you need more control over the dependency injection process, consider using @Qualifier annotation. The qualifier annotation helps disambiguate bean references when Spring otherwise could not do so this annotation is used to avoid confusion in the dependency injection.
To understand it more, let’s take a simple example of HelloWorldService
, let’s assume that we have 2 implementations of our HelloWorldService
public interface HelloWorldService {
void sayHello();
}
public class HelloWorldService1 implements HelloWorldService {
@Override
public void sayHello() {
}
}
public class HelloWorldService2 implements HelloWorldService {
@Override
public void sayHello() {
}
}
In case we want to Inject our HelloWorldService1 using @Autowire
annotation, Spring will not know which one of the two implementations to inject.
public class HelloWordTest {
@Autowired
private HelloWorldService helloWorldService;
}
To handle all similar issues where we want to let Spring know about which dependency to pick and inject, we can use @Qualifier
annotation.
@Autowired
@Resource(name = "helloService1")
private HelloWorldService helloWorldService;
1.4 @Bean
@Bean annotation is used to create a bean in the Spring Framework, we use this annotation at the method level
@Bean
public Customer customer() {
// instantiate and configure customer obj
return customer;
}
By default, the strategy for determining the name of a bean is to use the name of the @Bean
method, however, if we want to explicitly name our bean, we can always use “name” or “alias” value to do that.
@Bean({"user", "customer"})
public Customer customer() {
// instantiate and configure customer obj
return customer;
}
1.5 @Configuration
We use this annotation at the class level which defines Beans, think of @Configuration
annotation as a configuration using Java class (then traditional XML file to define Spring Beans)
@Configuration
public class ApplicationConfig {
@Bean
public OkHttpClient client(){
return new OkHttpClient.Builder()
.build();
}
@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
loggingFilter.setIncludeClientInfo(true);
loggingFilter.setIncludeQueryString(true);
loggingFilter.setIncludePayload(true);
loggingFilter.setIncludeHeaders(false);
return loggingFilter;
}
}
1.6 @ComponentScan
We use this annotation to configures component scanning directives for use with @Configuration
classes, we can specify base package from where we want Spring to scan packages. If we do not define specific packages, scanning will occur from the package of the class that declares this annotation.
1.7 @Lazy
Spring by default use eager initialization strategy i.e. all autowired dependencies will be created and configured at startup.If we do not want this to happen, we can use @Lazy
annotation to ensure he @Bean
or @Component
will not be initialized until referenced by another bean or explicitly retrieved from the enclosing BeanFactory.
@Configuration
@Lazy
public class AppConf {
@Bean
public MyBean bean() {
return new MyBean();
}
@Bean
public MyBean1 bean1() {
return new MyBean1();
}
//Bean2 will be eagerly loaded by Spring
@Bean
@Lazy(value = false)
public Bean2 bean2() {
return new Bean2();
}
}
For more detail, please read Guide to the Spring @Lazy Annotation
1.8 @Value
This is at the field or method/constructor parameter level that shows a default value expression for the affected argument. This is very similar to @Autowire
annotation but @Value
annotation will inject values from properties.
To understand it more, let’s take an example where we want to get some values from the property file, Let’s define our property file
user.name=Java Dev Journal
language=java
Here is our Java code
@Value("user.name")
private String username;
@Value("language")
private String language;
Please read @ConfigurationProperties in Spring Boot to understand how it works for Spring Boot.In this section, we will cover Stereotype Annotations provided by Spring Framework.
1.9 @Service
This is a class level annotation shows that an annotated class is a "Service"
, Apart from the fact that it is used to show that it’s holding the business logic, there’s no noticeable specialty that this annotation provides.
@Service("helloService")
public class HelloWorldService1 implements HelloWorldService {
@Override
public void sayHello() {
}
}
1.10 @Repository
This annotation is used on the classes which are working directly with the DB layer, @Repository
annotation shows that an annotated class is a "Repository"
.One of the different thing being performed by classes annotated with @Repository
annotation is to catch Platform specific exceptions and re-throw them as one of Spring’s unified unchecked exception.
1.11 @Component
We use this annotation to show a Spring-powered component. This is a general-purpose stereotype annotation showing that the class is a spring component. If we check definitions of @Service or @Repository
annotations
@Component
public @interface Service {
//
}
@Component
public @interface Repository {
//
}
we can safely say that @Service
or @Repository
annotations are special kinds of @Component
annotation.
1.12 @Lookp Annotation
To put it in simple words, lookup method injection is the process to override a Spring bean at the runtime. The constructor and property are the most common used dependency injection methods. Both the options happen during the initialization of the Bean. The @Lookup annotation in Spring is helpful when we like to implement a factory method which returns a new bean on every call without we implementing the method. Here are some of the most common use cases for the @Lookup
:
Please read @Lookup Annotation in Spring for more detail.
1.13 @Order Annotation
@Order annotation defines the sort order for an annotated component. This annotation is available from Spring 2.0. This annotation has an optional value argument which represents an order value as defined in the Ordered
interface. The default value is Ordered.LOWEST_PRECEDENCE
, showing lowest priority, similarly, the value Ordered.HIGHEST_PRECEDENCE
for overriding the highest priority.
For more detail, please read @Order in Spring
Summary
In this post, we get an introduction to Spring Framework Annotations. We checked different annotations provided by Spring Framework with information about when to use these Annotations.In the next article, we will cover some important Annotations provided by Spring Boot and Spring MVC framework.