一.回调方法
1.初始化方法
- 1.注解方式:@PostConstruct
- 2.实现InitiallizingBean接口
- 3. @Bean(initMethod = “initMethod”)
2.销毁方法
- 1.注解方式:@PreDestroy
- 2.实现DisposableBean接口
- 3.@Bean(destroyMethod = “destroyMethod”)
3.执行顺序
4.代码示例
package com.learning.beancallbackmethod;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @Author wangyouhui
* @Description bean定义
**/
public class UserService implements InitializingBean, DisposableBean {
@PostConstruct
public void postConstruct(){
System.out.println("初始化1");
}
@PreDestroy
public void preDestroy(){
System.out.println("销毁1");
}
@Override
public void destroy() throws Exception {
System.out.println("销毁2");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("初始化2");
}
public void initMethod(){
System.out.println("初始化3");
}
public void destroyMethod(){
System.out.println("销毁3");
}
}
package com.learning.beancallbackmethod;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author wangyouhui
* @Description 配置类
**/
@Configuration
public class MainConfig {
@Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public UserService userService(){
return new UserService();
}
}
package com.learning.beancallbackmethod;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Author wangyouhui
* @Description bean初始化方法、销毁方法
**/
public class Run {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
UserService bean = applicationContext.getBean(UserService.class);
// 容器关闭,bean才会销毁
applicationContext.close();
}
}