1.在定义 Bean 时指定初始化之前或销毁之前需要执行的方法;
public class User {
public void beforeInitMethod() {
System.out.println("User 初始化之前-------");
}
public void beforeDestoryMethod() {
System.out.println("User 销毁之前-------");
}
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
// setter and getter
}
@Configuration
public class ConfigBean {
@Bean(name = "username", initMethod = "beforeInitMethod", destroyMethod = "beforeDestoryMethod")
public User getUser() {
return new User("小刘", 20);
}
}
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigBean.class);
User user = (User) ctx.getBean("username");
System.out.println("Bean的名字:" + user.getName());
ctx.close();
}
}
2.通过 JDK 注解 @PostConstruct 和 @PreDestroy 实现
public class User {
@PostConstruct
public void beforeInitMethod() {
System.out.println("User 初始化之前-------");
}
@PreDestroy
public void beforeDestoryMethod() {
System.out.println("User 销毁之前-------");
}
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
// setter and getter
}
@Configuration
public class ConfigBean {
@Bean(name = "username")
public User getUser() {
return new User("小刘", 20);
}
}
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigBean.class);
User user = (User) ctx.getBean("username");
System.out.println("Bean的名字:" + user.getName());
ctx.close();
}
}
3.通过为 Bean 实现 InitializingBean 和 DisposableBean 接口
public class User implements InitializingBean, DisposableBean {
public void beforeInitMethod() {
System.out.println("User 初始化之前-------");
}
public void beforeDestoryMethod() {
System.out.println("User 销毁之前-------");
}
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void destroy() throws Exception {
beforeDestoryMethod();
}
@Override
public void afterPropertiesSet() throws Exception {
beforeInitMethod();
}
}
@Configuration
public class ConfigBean {
@Bean(name = "username")
public User getUser() {
return new User("小刘", 20);
}
}
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigBean.class);
User user = (User) ctx.getBean("username");
System.out.println("Bean的名字:" + user.getName());
ctx.close();
}
}