竹子建站官网,有哪些做笔译的网站,创意型网站建设,网站如何赚钱在Spring容器加入一个实现了BeanPostProcessor接口bean实例#xff0c;重写postProcessBeforeInitialization、postProcessAfterInitialization方法#xff0c;在方法里面写具体的实现#xff0c;从而达到Spring容器在初如化前或销毁时执行预定的程序#xff0c;方法如下重写postProcessBeforeInitialization、postProcessAfterInitialization方法在方法里面写具体的实现从而达到Spring容器在初如化前或销毁时执行预定的程序方法如下
1、pop.xml导包
dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.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 {Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {// TODO Auto-generated method stubSystem.out.println(前置处理);return null;}Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {// TODO Auto-generated method stubSystem.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);}Overridepublic String toString() {return User [id id , name name ];}public User() {super();}}
3、applicationContext.xml配置
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean iduser1 init-methodtestPrint destroy-methodtestPrint classtest.spring.model.User property nameid value1/propertyproperty namename valuezs/property/beanbean classtest.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 {Testpublic void testUser() {ConfigurableApplicationContext acnew ClassPathXmlApplicationContext(applicationContext.xml);User userac.getBean(User.class); System.out.println(user);ac.close();}}