一、@Bean指定初始化销毁方法
配置类:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
public class SpringConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public User user(){
System.out.println("user..被创建放入ioc容器。。。");
return new User();
}
}
User类中:
public class User {
public User() {
System.out.println("user...创建.........");
}
public void init() {
System.out.println("user...初始化.......");
}
public void destroy(){
System.out.println("user...销毁.......");
}
}
main方法测试:
在单实例下,对象生命周期在容器关闭的时候销毁
在多实例@Scope(“prototype”)下:容器不会管理bean,容器关闭的时候不会去销毁
二、通过实现InitializingBean, DisposableBean接口
配置类:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
public class SpringConfig {
@Bean
public User user(){
System.out.println("user..被创建放入ioc容器。。。");
return new User();
}
}
User类:
public class User implements InitializingBean, DisposableBean {
public User(){
System.out.println("user...创建.........");
}
@Override
public void destroy() throws Exception {
System.out.println("user...销毁.........");
}
//在对象创建 所有属性初始化好之后调用
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("user初始化...afterPropertiesSet().........");
}
}
main方法测试:
三、使用@PostConstruct, @PreDestroy注解
配置类:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
public class SpringConfig {
@Bean
public User user(){
System.out.println("user..被创建放入ioc容器。。。");
return new User();
}
}
User类:
public class User{
public User(){
System.out.println("user...创建.........");
}
@PreDestroy
public void destroy() {
System.out.println("user...销毁.........");
}
@PostConstruct
public void init() {
System.out.println("user初始化...........");
}
}
main方法测试:
四、BeanPostProcessor后置处理器
配置类:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
public class SpringConfig {
@Bean
public User user(){
System.out.println("user..被创建放入ioc容器。。。");
return new User();
}
}
User类:
public class User{
public User(){
System.out.println("user...创建.........");
}
@PreDestroy
public void destroy() {
System.out.println("user...销毁.........");
}
@PostConstruct
public void init() {
System.out.println("user初始化...........");
}
}
使用 BeanPostProcessor
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之前调用beanName:"+beanName+"......."+"bean:"+bean);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之后调用beanName:"+beanName+"..........."+"bean:"+bean );
return bean;
}
}
main方法: