Java Spring Boot Annotations

Spring Annotations

@Autowire

@Autowire is used to inject a dependency into an object.

There are two ways of using @Autowire, field injection and constructor injection.

Field injection

public class MyClass {
    @Autowire
    private Object someObject;
}

Constructor injection

public class MyClass {

    private final Object someObject

    @Autowire
    MyClass(Object someObject) {

        this.someOjbect = someObject;
    }
}

Construction injection is recommended over field inject is because it has several advantages:

  1. The dependencies are clearly identified.
  2. It makes testing simpler since there is no way to miss out a dependency during testing and you can guarantee that objects are going to be injected/instantiated in any other way outside of what is defined in the test.
  3. The dependencies can be final therefore increasing the robustness of the class
  4. Reflection is not required to set the dependencies. Instead of having to use the @InjectMocks annotation, the mocks can be created by you and you can inject them into the constructor.

Difference between @Controller and @RestController

@RestController annotation was released in Spring 4.

It eliminates the need for the @ResponseBody annotation in the mapped method.

This:

public @ResponseBody Employee getEmployee() {}

Can be replaced with this:

public Employee getEmployee(){}

Which simplifies the method.

@Qualifier Annotation

Autowiring (@Autowired) is the process by which Spring handles dependency injection.

But sometimes there are instances where there are more than one Bean of the same type that could be injected.

In these cases Spring does not know which Bean to inject and will then throw an error of NoUniqueBeanDefinitionException. This indicates that there is more than one bean available for autowiring.

In the example below, there are two components both of type Validator.

@Component("fooValidator")
public class FooValidator implements Validator {
 
    public String validate() {
        return "foo";
    }
}
 
@Component("barValidator")
public class BarValidator implements Validator {
 
    public String validate() {
        return "bar";
    }
}
 
@Component
public class FooService {
     
    @Autowired
    private Validator validator;
}

But Spring will not know which Validator to inject into the FooService, so will throw and exception.

We can use the @Qualifier annotation to tell Spring which component to use.

@Component
public class FooService {
     
    @Autowired
    @Qualifier("barValidator")
    private Validator validator;
}

@Service Annotation

@Service annotation is used for classes that provide some business functionalities. It is a type of Component.

A class annotated with @Service are automatically registered as Spring Beans [2].

When classpath scanning is performed by Spring, it will recognise this annotation and automatically initialise this class. This is part of the annotation based configuration that Spring performs.

Difference between @Component and @Bean

@Component autodetects and configures the beans using classpath scanning.

@Bean explicitly declares a specific bean rather than letting spring do it automatically.

Get @Valid Exception Errors

If you have a controller request mapping that uses the @Valid annotation to valid fields in the object in the request body the exceptions that @Valid throws can be caught using the Errors parameter.

@Valid throws the MethodArgumentNotValidException but this can be caught using the Errors parameter in the request mapping:

public ResponseEntity<> getUser(@Valid @RequestBody User user, Errors errors) {
    if (errors.hasErrors()) {
        // handle the errors
    }
    return new ResponseEntity(HttpStatus.OK);
}

References

[1] http://zetcode.com/spring/bean/

[2] https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-spring-beans-and-dependency-injection.html

[3] https://stackoverflow.com/a/33664636

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.