Spring Framework Annotations

 Introduction to Spring Framework Annotations

In this post, we will get a quick introduction to Spring Framework Annotations. We will explore different annotations along with few of the internal details for these Spring Framework Annotations.

 

Introduction

Java 5.0 introduced support for the annotations and very 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 defacto standard for Spring-based enterprise applications.

 

1. Spring Core Annotation

In this section, we will be covering Spring Framework Core Annotations.

1.1 @Required

@Required annotation is 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 is unable to inject the required bean, BeanInitializationException is thrown.

@Required
public void setClient(OkHttpClient client) {
    this.client = client;
}

 

1.2 @Autowired

@Autowired annotation is 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 given 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 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, you should consider using @Qualifier annotation.The qualifier annotation helps disambiguate bean references when Spring would otherwise not be able to do so, in short, this annotation is used to avoid confusion in the dependency injection.

To understand it more clearly, 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 bean in the Spring Framework, this annotation is used at the method level

@Bean
public Customer customer() {
    // instantiate and configure customer obj
    return customer;
}

By default,  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

This annotation is used at the class level which defines Beans, think of @Configuration annotation as configuration using Java class (than 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

This annotation is used to configures component scanning directives for use with @Configuration classes, we can specify base package from where we want Spring to scan packages.If specific packages are not defined, 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();
    }
}

 

1.8 @Value

This is at the field or method/constructor parameter level that indicates a default value expression for the affected argument. This is very similar to @Autowire annotation but @Value annotation will be used to inject values from properties.

To understand it more clearly, let’s take an example where we want to get some of the 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 be covering Stereotype Annotations provided by Spring Framework.

 

1.9 @Service

This is a class level annotation indicates that an annotated class is a "Service", Apart from the fact that it is used to indicate 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 indicates 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

This annotation is used to indicate a Spring-powered component.This is a general-purpose stereotype annotation indicating 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.

 

Summary

In this post, we get an introduction to Spring Framework Annotations. We checked a different kind of  Annotations provided by Spring Framework with information about when to use these Annotations.

In the next article, we will cover some of the important Annotations provided by Spring Boot and Spring MVC framework.

JavaDevJournal

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz