在Spring容器加入一个实现了BeanPostProcessor接口bean实例,重写postProcessBeforeInitialization、postProcessAfterInitialization方法,在方法里面写具体的实现,从而达到Spring容器在初如化前或销毁时执行预定的程序,方法如下:
1、pop.xml导包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.37</version>
</dependency>
<dependency>
2、写一个类实现BeanPostProcessor接口,同时写一个User实体类用于测试
实现类:
package test.spring.model;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class LifeBeanAware implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("前置处理");
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("后置处理");
return null;
}
}
User类:
/**
*Description:
*author: ljd
*@date 2024年7月2日
*@version 1.0
*/
package test.spring.model;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
System.out.println("user赋值");
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void testPrint() {
System.out.println("this is test init function");
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
public User() {
super();
}
}
3、applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user1" init-method="testPrint" destroy-method="testPrint" class="test.spring.model.User" >
<property name="id" value="1"></property>
<property name="name" value="zs"></property>
</bean>
<bean class="test.spring.model.LifeBeanAware"></bean>
</beans>
4、测试结果
/**
*Description:
*author: ljd
*@date 2024年7月2日
*@version 1.0
*/
package testSpring;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.spring.model.User;
public class TestSpring {
@Test
public void testUser() {
ConfigurableApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
User user=ac.getBean(User.class); System.out.println(user);
ac.close();
}
}