初始化
方式一 @PostConstruct
在Bean的方法上使用@PostConstruct注解
方式二 afterPropertiesSet()方法
实现InitializingBean接口重写afterPropertiesSet方法
方式三 在@Bean的属性中指定方法名
@Bean(initMethod = “初始化方法名”)
案例
创建一个具有多种方式初始化的Bean
public class InitDemoBean implements InitializingBean, BeanNameAware {
@PostConstruct
public void init1() {
System.out.println("初始化1->@PostConstruct");
}
@Override
public void setBeanName(String s) {
System.out.println("BeanNameAware执行");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("初始化2->InitializingBean接口,afterPropertiesSet()方法实现");
}
public void initMethod() {
System.out.println("初始化3->@Bean initMethod属性指定方法名");
}
}
``
创建Springboot程序
```java
@SpringBootApplication
public class InitDemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(InitDemoApplication.class, args);
context.close();
}
@Bean(initMethod = "initMethod")
public InitDemoBean initDemoBean() {
return new InitDemoBean();
}
}
执行结果
BeanNameAware执行
初始化1->@PostConstruct
初始化2->InitializingBean接口,afterPropertiesSet()方法实现
初始化3->@Bean initMethod属性指定方法名
总结
@PostConstruct > InitializingBean接口,afterPropertiesSet()方法实现 > @Bean initMethod属性指定方法名
销毁
方式一 @PreDestroy注解
在方法上使用@PreDestroy注解
方式二 destroy()方法
实现DisposableBean接口 重写
方式三 在@Bean的属性中指定方法名
@Bean(destroyMethod = “销毁方法名”)
案例
创建一个具有多种方式销毁的Bean
public class DestroyDemoBean implements DisposableBean {
@PreDestroy
public void destroy1() {
System.out.println("销毁1->@PreDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("销毁2->DisposableBean接口实现 destroy()方法");
}
public void destroyMethod() {
System.out.println("销毁3->@Bean destroyMethod属性指定方法名");
}
}
``
创建Springboot程序
```java
@SpringBootApplication
public class DestroyDemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DestroyDemoApplication.class, args);
context.close();
}
@Bean(destroyMethod = "destroyMethod")
public DestroyDemoBean destroyDemoBean() {
return new DestroyDemoBean();
}
}
执行结果
销毁1->@PreDestroy
销毁2->DisposableBean接口实现 destroy()方法
销毁3->@Bean destroyMethod属性指定方法名
总结
@PreDestroy > DisposableBean接口实现 destroy()方法 > @Bean destroyMethod属性指定方法名
评论区