Spring Framework Summary-About DI

[Thorough introduction to Spring Java application development with Spring Framework](https://www.amazon.co.jp/Spring thorough introduction-Java application development with Spring-Framework-NTT Data Co., Ltd./dp/4798142476/) And I have summarized the parts that I think are important. (I supplemented it a little independently.) The number of pages of the reference book is listed so that you can look back at it later.

This time, it's an article about DI.

Type of injection

There are the following three types of DI in Spring. (P.23)

Setter injection

How to DI for setter arguments.

Merit: DI can be performed while keeping the existing Setter. Disadvantages: Troublesome compared to field injection.

@Component
public class UserServiceImpl implements UserService {
    private UserRepository userRepository;
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
}

Constructor injection

How to DI for constructor arguments.

Merit: The field can be made immutable by adding the final modifier. Disadvantages: Troublesome compared to field injection.

@Component
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    @ConstructorProperties({"userRepository", "passwordEncoder"})
    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }
}

Field injection

How to DI for a field in a class.

Merit: The amount of code is small and it is the simplest to write. Disadvantage: The code is supposed to do DI.

@Component
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
}

Target of component scan

A component scan is to scan the class loader and automatically register a specific class in the DI container. (P.35)

By default, classes with the following annotations are targeted.

Annotation Description
@Controller A component that plays the role of C in the MVC pattern. The component to which this annotation is attached processes the request / response from the client.
@Service Annotation that indicates that it is a component that implements business logic.
@Repository A component that provides processing related to data persistence. Implement CRUD processing of data using ORM etc.
@Component Components that do not fit into the above three. Give to utility class etc.
@Configuration Write before the class declaration. This annotation indicates that this class is responsible for setting the bean. Always attach this to the Bean configuration class.
@RestController Give to the controller for WebAPI that returns JSON, XML, etc.
@ControllerAdvice When handling exceptions across Controllers, add this annotation to the class for exception handling. Used for ExceptionHandler class.
@ManagedBean Originally, it represents a Managed Bean managed by JSF. Spring@It seems to have the same meaning as when Component is attached.
@Named Originally Java(EE)It represents the injection target in the system. Spring@It seems to have the same meaning as when Component is attached.

Bean scope

In Spring, the component registered in the DI container is called ** "Bean" **, and the Configuration is called "Bean definition". Getting a bean from a DI container is called "lookup". (P.17)

Scope available in Spring Framework

A list of scope specifications available in Spring. (P.39)

scope Description
singleton
(Default)
Create a bean instance when starting the DI container and share and use the same instance. If the scope is not set, it will be treated as a singleton.
prototype Create an instance every time you get a bean. For thread unsafe beans, prototype is used because singleton scope cannot be used.
session Create a bean instance for each HTTP session. Valid only for web applications.
request Create a bean instance for each HTTP request. Valid only for web applications.
globalSession Create an instance for each Global Session in the portlet environment. Valid only for Web applications that support portlets.
application Create an instance of Bean for each context of Servlet. Valid only for web applications.
Custom scope(Unique naming) Create a bean instance with your own defined rules.

Be careful when injecting different scopes in the same class. (P.41)

You can imagine what kind of site a Web application that supports portlets is by searching for images on "Portlet Web".

Bean life cycle

The life cycle of a bean managed by a DI container consists of the following three phases. (P.47)

Of the above three phases, most of the time is the usage phase.

Initialization phase

  1. Read Bean → Prepare to generate Bean.
  2. Dependency resolution → Bean instance generation and injection execution.
  3. Post Construct → Processing after instance creation. You can use the injected bean.
@Component
public class UserServiceImpl implements UserService {
    @PostConstruct
    void pupulateCache() {
        //Cache generation process
    }
}

End phase

In the end phase, a pre-destruction process called "Pre Destroy" is performed. (P.50)

@Component
public class UserServiceImpl implements UserService {
    @PreDestroy
    void clearCache() {
        //Cache discard process
    }
}

Reference source

site

Implementation of DI by annotation (2/5): Introduction to Spring Framework for beginners Various return values in Spring MVC controller --Qiita Exceptional handling in Spring-Qiita Engineer's time killing: Spring management of Managed Bean with Spring + JSF

Books

[Thorough introduction to Spring Java application development using Spring Framework](https://www.amazon.co.jp/Thorough introduction to Spring-Java application development using Spring-Framework-NTT Data Co., Ltd./dp/4798142476/)

Recommended Posts

Spring Framework Summary-About DI
[Java] Spring DI ③
Spring Framework study notes [Part 1] DI container
[Spring Framework] Configuration split
Spring Framework multilingual support
1. Start Spring framework from 1
About DI of Spring ①
First Spring Boot (DI)
About DI of Spring ②
Major changes related to Spring Framework 5.0 DI container
Spring Basics ~ DI Edition ~
Spring Framework self-study memo series_1
About Spring Framework context error
Introduction to Spring Boot ① ~ DI ~
[Java] How Spring DI works
About Spring DI related annotations
Spring Framework 5.0 Summary of major changes
spring framework Simple study memo (2): AOP
Java --Jersey Framework vs Spring Boot
Spring Framework tools for Java developer
[Java] Spring DI ④ --Life cycle management
Test Spring framework controller with Junit
Introducing Basic Authentication on Heroku [Spring Framework]
Major changes related to Spring Framework 5.0 Test
Spring Framework bean definition XML: custom tag
Why spring consider as a lightweight framework
About the initial display of Spring Framework
Major changes in Spring Framework 5.0 core functionality
Features of spring framework for java developers
DI SessionScope Bean in Spring Boot 2 Filter