[JAVA] Bean scope and Bean Life Cycle

Bean scope

Bean scope Unless otherwise configured in Spring, the default bean scope consists of a singleton.

singleton : spring default bean scope prototype: The spring creates a new instance (every time the getBean () method is called) on application request. request: HTTP Instantiated for each request and disappears when the request ends. session: Instantiated for each HTTP session and disappears when the session ends. global session: For portrait-based web applications, the global session scope can be shared between all portraits in a portal application using Spring MVC like empty. thread: Creates a new bean instance when requested by a new thread. The same instance is always returned for requests from the same thread. custom: Use by implementing org.pringframework.beans.factory.config.Scope and registering the custom scope in the spring settings.

There are two ways to specify the free scope, one is by using XML and the other is by using annotation.

XML

<bean id="memberBean" class="com.java.Member" scope="singleton"/>

Annotation

package com.java.pojo;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
 
@Service("memberBean")
@Scope("singletone")
public class Member {
}

Bean Life Cycle

Bean Life Cycle The free life cycle basically goes through the stages of generation, dependency setting, initialization, and disappearance. But it depends on what kind of container you use.

Bean Factory is the simplest form of container that supports basic dependency injection, deferring empty generation until the getBean () method is called. Application Context is a container that inherits BeanFactory and has all the functions of BeanFactory and has additional functions. The Application context can be used by creating and loading all the free space before the context starts and copying it at any time.

Initialize & Destory method The Bean Initialize method is a method that is executed after the Bean Object is created and finishes DI. Generally, if Object initialization work is required, it is handled by the generator, but if there is initialization work after initialization after the bean is injected by DI, initialization is performed using the initialization method. I will proceed.

@PostConstruct

@Slf4j
@Component
public class SimpleBean {

    @PostConstruct
    public void postConstruct() {
        log.info("postConstruct");
    }
}

@PreDestroy

@Slf4j
@Component
public class SimpleBean {

    @PreDestroy
    public void preDestroy() {
        log.info("preDestroy");
    }
}

Recommended Posts

Bean scope and Bean Life Cycle
Activity life cycle
About Bean and DI
About the Android life cycle
[Java] Spring DI ④ --Life cycle management