@[TOC]
1 指定初始化和销毁方法
创建
Car
类public class Car { public Car() { System.out.println("car constructor......"); } public void init(){ System.out.println("car ...init..."); } public void destory(){ System.out.println("car ...destory..."); } }
写配置类
@Configuration public class MainConfigOfLifeCycle { @Bean(value = "car",initMethod="init",destroyMethod = "destory") public Car car(){ return new Car(); } }
- 测试
@Test public void test01(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class); System.out.println("容器创建完成"); context.close(); }
2 使用接口
InitializingBean
和DisposableBean
实现初始化和销毁 - 新建Cat类实现接口
InitializingBean
和DisposableBean
```java
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class Cat implements InitializingBean, DisposableBean {
public Cat() {
System.out.println("cat constructor....");
}
//容器关闭时调用
@Override
public void destroy() throws Exception {
System.out.println("cat ... destroy ....");
}
//Bean创建完成,并且属性都复制后执行
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("cat ... afterPropertiesSet ...");
}
}
* 注入IOC容器
```java
@Configuration
@ComponentScan("com.yunfeng.spring2.entity")
public class MainConfigOfLifeCycle {}
- 测试
@Test public void test01(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class); System.out.println("容器创建完成"); context.close(); }
3 使用JSR250中的
```java@PreDestroy
和@PostConstruct
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class Dog {
public Dog() {
System.out.println("Dog constructor....");
}
//容器关闭时调用
@PreDestroy
public void destroy() throws Exception {
System.out.println("Dog ... destroy ....");
}
//Bean创建完成,并且属性都复制后执行
@PostConstruct
public void afterPropertiesSet() throws Exception {
System.out.println("Dog ... PostConstruct ...");
}
}
# 4 BeanPostProcessor后置处理器
* 在bean初始化前后进行一些处理工作
```java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
/**
* 后置处理器:初始化前后进行处理工作
*/
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
//初始化前执行
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization..." + beanName + bean);
return bean;
}
//初始化后执行
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization..." + beanName + bean);
return bean;
}
}