spring bean初始化和销毁

时间:2023-03-09 08:06:39
spring bean初始化和销毁

spring bean的创建与消亡由spring容器进行管理,除了使用<bean><property/></bean>进行简单的属性配置之外,spring支持更人性化的方法

  • @PostConstruct @PreDestroy
  • xml的init-method和destroy-method
  • 实现InitializingBean和DisposableBean接口
 public class BeanInitMethod implements InitializingBean, DisposableBean {

     private int step;

     public int getStep() {
return step;
} public void setStep(int step) {
this.step = step;
} @PostConstruct
public void postConstruct() {
System.out.println("initialized by annotation");
step = 1;
} @PreDestroy
public void predestroy() {
System.out.println("destroyed by annotation");
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("initialized by interface");
step = 2;
} @Override
public void destroy() throws Exception {
System.out.println("destroyed by interface");
} public void initFunc() {
System.out.println("initialized by xml");
step = 3;
} public void destroyFunc() {
System.out.println("destroyed by xml");
} public static void main(String[] argv) {
BeanInitMethod beanInitMethod;
BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");
beanInitMethod = (BeanInitMethod) beanFactory.getBean("initTestBean"); System.out.println("step=" + beanInitMethod.getStep()); System.out.println("program is done");
} }

对于“注解方式”还需要开启注解的支持,在上下文xml配置文件加入

<context:annotation-config/>

对于xml配置方式,则需要加入

<bean id="initTestBean" class="edu.xhyzjiji.cn.spring.BeanInitMethod" init-method="initFunc" destroy-method="destroyFunc"/>

当bean实例被创建时,会依据以下顺序执行初始化

initialized by annotation
initialized by interface
initialized by xml
step=3
program is done