普通Java程序需要使用((AbstractApplicationContext)context).close();
显式指定关闭spring容器,destory
方法才会运行
- 普通Bean对象通过
init-method
和destroy-method
指定初始化与销毁方法
public class Student implements Serializable {
//......
public void init(){
log.debug("init...");
}
public void destory(){
log.debug("destory...");
}
}
注解:
@Bean(initMethod = "init",destroyMethod = "destory")
public Student student(){
return new Student();
}
xml:
<bean class="com.hjf.student.entity.Student" id="student" init-method="init" destroy-method="destory"/>
组件形式的注解:
- 通过
@PostConstruct
和@PreDestroy
指定初始化和销毁方法
@Data
@Slf4j
@Service
public class MybatisCardServiceImpl implements MybatisCardService {
@PostConstruct
public void init(){
log.debug("init...");
}
@PreDestroy
public void destory(){
log.debug("destory...");
}
}
- 实现接口方式:通过实现
InitializingBean
的afterPropertiesSet()
方法和DisposableBean
的destroy()
方法指定初始化和销毁
@Component
@Slf4j
public class SomeClass implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
log.debug("init...");
}
@Override
public void destroy() throws Exception {
log.debug("destory");
}
}
初始化前后的处理:实现BeanPostProcessor
类,该接口的实现类会拦截spring容器内所有的bean,并在init
方法执行前调用postProcessBeforeInitialization()
,在init
方法执行后调用postProcessAfterInitialization()
@Component
@Slf4j
public class SomeClass implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Student) {
log.debug("after construct before init");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Student) {
log.debug("after init");
}
return bean;
}
}
运行结果如下: