Spring Bean 生命周期之PostConstruct、P

2024-01-27  本文已影响0人  Tinyspot

1. @PostConstruct

package javax.annotation;

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

2. @PreDestroy

package javax.annotation;

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PreDestroy {
}

3. Spring Bean 初始化和销毁

3.1 Java 注解:@PostConstruct, @PreDestroy

@Component
@Slf4j
public class UserConfig {

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

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

3.2 xml 配置方式

<bean id ="userConfig" class="com.example.concrete.starter.config.UserConfig" init-method="init" destroy-method="detory"></bean>

3.3 @Bean 注解方式

@Configuration
public class BusinessManager {
    
    @Bean(name = "userConfig", initMethod="init",destroyMethod="destroy")
    public UserConfig userConfig(){
        return new UserConfig();
    }
}
@Slf4j
public class UserConfig {
    public void init() {
        log.info("UserConfig init...");
    }

    public void destroy() {
        log.info("UserConfig destroy...");
    }
}

4. 案例

@Slf4j
public class UserConfig {

    private final List<String> shopList = new CopyOnWriteArrayList<>();

    public List<String> getShopList() {
        return shopList;
    }

    public UserConfig() {
        log.info("UserConfig Constructor....");
    }

    public void init() {
        log.info("UserConfig init...");
    }

    public void destroy() {
        log.info("Spring IoC容器关闭, UserConfig destroy...");
    }

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

    @PreDestroy
    public void destroyBean() {
        log.info("Spring IoC容器关闭, UserConfig destroyBean ...");
    }
}
@Configuration
public class BusinessManager {

    @Bean(name = "userConfig", initMethod="init",destroyMethod="destroy")
    public UserConfig userConfig(){
        return new UserConfig();
    }
}

打印日志:

2024-01-28 15:38:17.769  INFO 7245 --- [           main] c.e.concrete.starter.config.UserConfig   : UserConfig Constructor....
2024-01-28 15:38:17.770  INFO 7245 --- [           main] c.e.concrete.starter.config.UserConfig   : UserConfig initBean...
2024-01-28 15:38:17.770  INFO 7245 --- [           main] c.e.concrete.starter.config.UserConfig   : UserConfig init...

2024-01-28 15:38:41.011  INFO 7245 --- [ionShutdownHook] c.e.concrete.starter.config.UserConfig   : Spring IoC容器关闭, UserConfig destroyBean ...
2024-01-28 15:38:41.011  INFO 7245 --- [ionShutdownHook] c.e.concrete.starter.config.UserConfig   : Spring IoC容器关闭, UserConfig destroy...
上一篇下一篇

猜你喜欢

热点阅读