在Spring中我们可以通过InitializingBean、@PostConstruct、以及制定init-method等方式在bean初始化时做一些初始化相关的操作,以及通过DisposableBean、@PreDestroy和destroy-method等方式在bean销毁时执行一些销毁操作。那么这些不同方式的执行顺序是什么呢?接下来我们通过实战来看下具体的执行顺序。
定义bean
package com.example.demo.service;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class HelloService implements InitializingBean, DisposableBean {
private String name;
public HelloService(String name) {
this.name = name;
}
@PostConstruct
public void postConstruct() {
System.out.println("PostConstruct name=" + name);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean name=" + name);
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean name=" + name);
}
@PreDestroy
public void preDestroy() {
System.out.println("PreDestroy name=" + name);
}
public void initMethod() {
System.out.println("initMethod name=" + name);
}
public void destroyMethod() {
System.out.println("destroyMethod name=" + name);
}
}
xml中配置bean声明
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.example.demo.service.HelloService" init-method="initMethod" destroy-method="destroyMethod">
<constructor-arg index="0" value="chyang" />
</bean>
</beans>
run项目
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource(locations = {"classpath:applicationContext.xml"})
public class ArthasDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ArthasDemoApplication.class, args);
}
}
执行结果
PostConstruct name=chyang
InitializingBean name=chyang
initMethod name=chyang
PreDestroy name=chyang
DisposableBean name=chyang
destroyMethod name=chyang
结论
- 初始化执行顺序:constructor(构造器) -> PostConstruct -> InitializingBean -> init-method
- 销毁执行顺序:PreDestroy -> DisposableBean -> destroy-method

被折叠的 条评论
为什么被折叠?



