若是咱們須要在Spring容器完成Bean的實例化,配置和其餘的初始化先後後添加一些本身的邏輯處理。java
編寫InitHelloWorld.javaspring
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.xmlide
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.javapost
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 }
運行輸出this
BeforeInitialization : helloWorld Bean is going through init. AfterInitialization : helloWorld Your Message : Hello World! Bean will destroy now.
能夠看到初始化bean的先後分別調用了postProcessBeforeInitialization和postProcessAfterInitialization方法spa