spring 中初始化和销毁有三种办法
- 实现接口 DisposableBean ,initilzingBean
- 使用注解 @PostConstructor, @PreDestory
- xml 配置 init-methods, destory-method , 或者在 @Bean(initMethod = "",destroyMethod="")
代码如下
config 配置Bean
package com.shanjiancaofu.ad.service.impl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
// initMethod 指定类的初始化方法, destroyMethod 指定类的销毁方法
@Bean(initMethod = "init", destroyMethod = "destroyMethod")
User user() {
return new User();
}
}
User 类
package com.shanjiancaofu.ad.service.impl;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
class User implements InitializingBean, DisposableBean {
public String userName;
public User() {
System.out.println("User constructor");
}
public void init() {
this.userName = "initName";
System.out.println(" user init. ....");
}
public void destroyMethod() {
this.userName = "destroyName";
System.out.println(" user destroy. ....");
}
@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy ...");
}
@PostConstruct
public void postConstruct() {
System.out.println(" @PostConstruct. ....");
}
@Override
public String toString() {
return "user:" + this.userName;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean destroy");
}
}
启动spring 应用 控制台输出:
User constructor
@PostConstruct. ....
InitializingBean afterPropertiesSet
user init. ....
关闭spring 应用 控制台输出:
@PreDestroy ...
DisposableBean destroy
user destroy. ....
和开头我们总结的顺序结论一致. 重要的是,类的构造器是最先执行的.
路过点赞, 月入10 W
网友评论