BeanPostProcessor 是 Spring 容器提供的擴展點,允許在 Bean 實例化、依賴注入完成、初始化前後插入自定義邏輯。介面定義:
public interface BeanPostProcessor {
// 初始化前回調 (如 @PostConstruct 前)
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
// 初始化後回調 (如 @PostConstruct 後)
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
Ordered 介面控制執行順序ApplicationContext 啟動時自動掃描並註冊所有實作類package com.example.spring.lifecycle;
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."); }
}
package com.example.spring.lifecycle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class InitHelloWorld implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeforeInitialization: " + beanName);
return bean; // 可返回代理對象、包裝對象或原對象
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("AfterInitialization: " + beanName);
return bean;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloWorld" class="com.example.spring.lifecycle.HelloWorld"
init-method="init" destroy-method="destroy">
<property name="message" value="Hello World!"/>
</bean>
<!-- 註冊後置處理器,無需指定 id,容器自動識別 -->
<bean class="com.example.spring.lifecycle.InitHelloWorld"/>
</beans>
package com.example.spring.lifecycle;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
// 註冊關閉鉤子,確保 destroy-method 被調用
context.registerShutdownHook();
}
}
BeforeInitialization: helloWorld
Bean is going through init.
AfterInitialization: helloWorld
Your Message: Hello World!
Bean will destroy now.
Spring AOP 的 AnnotationAwareAspectJAutoProxyCreator 即實作 BeanPostProcessor,在初始化後為目標 Bean 建立代理。
public class ValidationPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 掃描 @NotNull、@Valid 等註解進行驗證
// 可拋出異常阻止 Bean 初始化
return bean;
}
}
注意區別:BeanFactoryPostProcessor 作用於 Bean 定義元資料 (如修改屬性值、掃描註解),在實例化前執行;BeanPostProcessor 作用於 Bean 實例。
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ServiceInterface) {
return Proxy.newProxyInstance(...); // 返回動態代理
}
return bean;
}
Ordered 或加 @OrderBeanPostProcessor 的功能性介面或 SmartInitializingSingletonBeanPostProcessor 是 Spring 擴展性的核心支柱,AOP、事務、驗證、配置綁定等眾多功能均建立於此。理解其生命週期位置與能力邊界,是掌握 Spring 進階開發的關鍵。