一、概述
bean的生命周期的回调方法主要分两种,一种是初始化时进行调用,另外一种是销毁时进行调用。但是不管是初始化还是销毁,都对应着三种方式。
二、实现方式
2.1、注解方式
java
@PostConstruct + @PreDestroy
java
@Component
public class UserService {
public UserService() {
System.out.println("UserService的构造方法执行了...");
}
@PostConstruct
public void init() {
System.out.println("UserService 初始化...");
}
@PreDestroy
public void destroy () {
System.out.println("UserService 销毁...");
}
}
2.2、实现接口方式
java
@Component
public class UserService2 implements InitializingBean, DisposableBean {
public UserService2() {
System.out.println("UserService2的构造方法执行了...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("UserService2 初始化...");
}
@Override
public void destroy() throws Exception {
System.out.println("UserService2 销毁...");
}
}
2.3、通过指定initMethod和destoryMethod方式
java
public class UserService3 {
public UserService3() {
System.out.println("UserService3的构造方法执行了...");
}
public void init() {
System.out.println("UserService3 初始化...");
}
public void destroy() {
System.out.println("UserService3 销毁...");
}
}
java
@Configuration
@ComponentScan(basePackages = "org.star")
public class MySpringConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public UserService3 userService3() {
return new UserService3();
}
}