[Java] Spring DI ④ --Life cycle management
What is DI lifecycle management?
- DI allows you to set the scope of an instance
- Scope is set with @Scope annotation
- Default is singleton, only one instance can be created
- Be careful if the field has instances with different scopes
What is lifecycle management?
- Manage instance creation (new) and destruction
- To destroy the instance created by new, put null in the variable and free the memory
- However! ** For fields with @Autowired, Spring will do it for you, even if it's not null! ** **
- Moreover, when using the Servlet ** Spring will also register the scope of the instance! ** (Servlet is a function to register an instance in Session scope or Request scope)
- Note: Make sure you know when the instance will be destroyed
What is a scope?
- Instance expiration date
- Example: Variables declared in an if statement as Java local variables cannot be used outside the if statement because the scope is inside the if statement.
- Session scope
- Expiration date from user login to log out
- Request scope
- One HTTP request expires
- Example: Request scope range from user registration screen to registration result screen
How to use Scope
- Specify which scope to register in the annotation with @Scope annotation as shown below.
- In addition to @Component, @Scope annotation can be used for @Bean, @Controller, etc.
- ** Easy to create and destroy instances **
@Component
@Scope("prototype")
public class SampleComponent{
}
Scope specified by @Scope
- singleton
- Default configuration
- Create only one instance when Spring starts,
- Share and use one instance after creation
- prototype
- An instance is created every time you get a bean
- session
- An instance is created for each HTTP session. Used only for web applications
- request
- An instance is created for each HTTP request. Used only for web applications
- globalSession
- Instance is generated for each GrobalSession in the portlet environment
- Used only for web applications that support portlets
- application
- Instance is created for each context of Servlet. Only available for web applications.
Note 1: The default is singleton
- If @Scope is not added, the instance will be created as a singleton.
- With a singleton, only one instance of an object can be created, and you cannot even create a second or more instance.
-
- A singleton is usually sufficient for the scope of @Controller, @Service, and @Repository.
Note 2: If the field has instances with different scopes
- If an instance of singleton scope has an object of prototype scope, ** Bean with prototype scope (hereinafter referred to as PrototypeComponent) becomes singleton scope **
//It becomes a singleton scope
@Component
@Scope("prototype")
public class PrototypeComponent{
}
@Component
public class SingletonComponent{
@Autowired
private PrototypeComponent component;
}