1.注解方式
在 bean 初始化时会经历几个阶段,首先可以使用注解 @PostConstruct
, @PreDestroy
来在 bean 的创建和销毁阶段进行调用:
@Component
public class AnnotationBean {
private final static Logger LOGGER = LoggerFactory.getLogger(AnnotationBean.class);
@PostConstruct
public void start(){
LOGGER.info("AnnotationBean start");
}
@PreDestroy
public void destroy(){
LOGGER.info("AnnotationBean destroy");
}
}
2.实现InitializingBean, DisposableBean接口
@Service
public class SpringLifeCycleService implements InitializingBean,DisposableBean{
private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleService.class);
@Override
public void afterPropertiesSet() throws Exception {
LOGGER.info("SpringLifeCycleService start");
}
@Override
public void destroy() throws Exception {
LOGGER.info("SpringLifeCycleService destroy");
}
}
3.JAVA Config方式
@Configuration
public class LifeCycleConfig {
@Bean(initMethod = "start", destroyMethod = "destroy")
public SpringLifeCycle create(){
SpringLifeCycle springLifeCycle = new SpringLifeCycle() ;
return springLifeCycle ;
}
}
public class SpringLifeCycle{
private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycle.class);
public void start(){
LOGGER.info("SpringLifeCycle start");
}
public void destroy(){
LOGGER.info("SpringLifeCycle destroy");
}
}
4. XML配置方式
<bean class="com.crossoverjie.spring.SpringLifeCycle" init-method="start" destroy-method="destroy">
</bean>
网友评论