close
BeanPostProcessor可以針對初始化前後做一些修正(如:初始化前顯示為小寫,修正後為大寫等)
HelloWorld.java
package com.example ; public class HelloWorld { private String message ; public void init(){ System.out.println("Initialization now") ; } public void getMessage(){ System.out.println("Your Message : " + message); } public void setMessage(String message) { this.message = message; } public void destroy(){ System.out.println("Destory now") ; } }
Main.java
package com.example ; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); } }
PostHelloWorld.java
package com.example ; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class PostHelloWorld implements BeanPostProcessor{ @Override public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { System.out.println("After Destory..."); return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { System.out.println("Before Initialization...") ; return bean; } }
Beans.xml
結果顯示如下所示:
Before Initialization... Initialization now After Destory... Your Message : Hello World! Destory now
全站熱搜
留言列表