Java框架spring 学习笔记(四):BeanPostProcessor接口

时间:2021-09-02 15:18:04

如果我们需要在Spring容器完成Bean的实例化,配置和其他的初始化前后后添加一些自己的逻辑处理。

编写InitHelloWorld.java

 package com.example.spring;

 import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; public class InitHelloWorld implements BeanPostProcessor{
//初始化Bean前
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Befor Initialization :"+beanName);
return bean;
} //初始化Bean后
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("After Initialization :"+beanName);
return bean;
}
}

编写Beans.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="helloWorld" class="com.example.spring.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World"></property>
</bean> <bean class="com.example.spring.InitHelloWorld"></bean>
</beans>

编写HelloWorld.java

 package com.example.spring;

 public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
} public void getMessage(){
System.out.println("Your Message : " + message);
}
//定义初始化方法
public void init(){
System.out.println("Bean is going through init.");
}
//定义销毁方法
public void destroy(){
System.out.println("Bean will destroy now.");
}
}

运行输出

BeforeInitialization : helloWorld
Bean is going through init.
AfterInitialization : helloWorld
Your Message : Hello World!
Bean will destroy now.

可以看到初始化bean的前后分别调用了postProcessBeforeInitialization和postProcessAfterInitialization方法