四种方法
- @Bean(initMethod="init-mathod-name",destroy="destroy-method-name")
- @PostConstruct和@PreDestroy
- 实现InitializingBean,DisposableBean
- 实现BeanPostProcessor
@Bean(initMethod="init-mathod-name",destroy="destroy-method-name")
//bean
public class ABean{
public void init() {
//dosomthing
}
public void destroy() {
//do destroy
}
}
// config文件
@Configuration
public class Config {
@Bean(initMethod="init",destroy=”destroy")
public ABean aBean() {
return new ABean();
}
}
@PostConstruct和@PreDestroy
@Component
public class AComponent {
@PostConstructor
public void postConstructor () {
// do something
}
@PreDestroy
public void preDestroy() {
//do some thing
}
}
实现InitializingBean,DisposableBean
@Component
public class AComponent implements InitializingBean,DisposableBean{
@Override
public void destroy() throws Exception {
//do something
}
@Override
public void afterPropertiesSet() throws Exception {
//do something
}
}
实现BeanPostProcessor
@Component
public class AComponent DisposableBean{
@Override
public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException {
//do something
}
@Override
public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException {
//do something
}
}
Spring底层对BeanPostProcessor的应用
可结合ApplicationAware接口和BeanPostProcessor,处理各类注解
网友评论