如果我们需要在Spring容器完成Bean的实例化,配置和其他的初始化前后后添加一些自己的逻辑处理。
编写InitHelloWorld.java
1 package com.example.spring; 2 3 import org.springframework.beans.BeansException; 4 import org.springframework.beans.factory.config.BeanPostProcessor; 5 6 public class InitHelloWorld implements BeanPostProcessor{ 7 //初始化Bean前 8 @Override 9 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 10 System.out.println("Befor Initialization :"+beanName); 11 return bean; 12 } 13 14 //初始化Bean后 15 @Override 16 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 17 System.out.println("After Initialization :"+beanName); 18 return bean; 19 } 20 }
编写Beans.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <bean id="helloWorld" class="com.example.spring.HelloWorld" 7 init-method="init" destroy-method="destroy"> 8 <property name="message" value="Hello World"></property> 9 </bean> 10 11 <bean class="com.example.spring.InitHelloWorld"></bean> 12 </beans>
编写HelloWorld.java
1 package com.example.spring; 2 3 public class HelloWorld { 4 private String message; 5 public void setMessage(String message){ 6 this.message = message; 7 } 8 9 public void getMessage(){ 10 System.out.println("Your Message : " + message); 11 } 12 //定义初始化方法 13 public void init(){ 14 System.out.println("Bean is going through init."); 15 } 16 //定义销毁方法 17 public void destroy(){ 18 System.out.println("Bean will destroy now."); 19 } 20 }
运行输出
BeforeInitialization : helloWorld Bean is going through init. AfterInitialization : helloWorld Your Message : Hello World! Bean will destroy now.
可以看到初始化bean的前后分别调用了postProcessBeforeInitialization和postProcessAfterInitialization方法