理解 Bean 的生命週期,是理解 Spring 整體運行流程的關鍵一環。在 IOC 容器中,Bean 從誕生到銷毀的每個節點都由容器親自管理。
初始化與銷毀方法通過聲明中的 init-method 與 destroy-method 屬性指定。
public class Life {
private String lifeName;
public Life() {
System.out.println("constructor....");
}
public void setLifeName(String lifeName) {
System.out.println("setLifeName....");
this.lifeName = lifeName;
}
public void initMethod() {
System.out.println("initMethod....");
}
public void destroyMethod() {
System.out.println("destroyMethod....");
}
public void targetMethod() {
System.out.println("targetMethod....");
}
}
<bean class="com.linuxidc.spring.bean.Life" id="life"
init-method="initMethod" destroy-method="destroyMethod">
<property name="lifeName" value="myLife"/>
</bean>
@Test
public void test03() {
Life life = ctx.getBean(Life.class);
life.targetMethod();
}
控制台輸出:
constructor.... setLifeName.... initMethod.... targetMethod....
順序清楚:構造 → 屬性注入 → 初始化 → 使用。銷毀方法則在容器關閉時才被觸發,單純的 getBean 看不到它。
Bean 後置處理器允許在調用初始化方法前後對 Bean 做額外加工,並會對 IOC 容器中的每個 Bean 實例逐一生效。使用方式是實現 BeanPostProcessor 接口的兩個方法:
postProcessBeforeInitialization(Object bean, String beanName)postProcessAfterInitialization(Object bean, String beanName)public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof Life) {
System.out.println("life's postProcessBeforeInitialization....");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof Life) {
System.out.println("life's postProcessAfterInitialization....");
}
return bean;
}
}
<bean class="com.linuxidc.spring.processor.MyBeanPostProcessor"/>
<bean class="com.linuxidc.spring.bean.Life" id="life"
init-method="initMethod" destroy-method="destroyMethod">
<property name="lifeName" value="myLife"/>
</bean>
postProcessBeforeInitialization();postProcessAfterInitialization();輸出驗證:
constructor.... setLifeName.... life's postProcessBeforeInitialization.... initMethod.... life's postProcessAfterInitialization.... targetMethod....
後置處理器的 postProcessAfterInitialization 是 Spring 埋本合同週期最重的一鉤子:@Autowired 的注入、AOP 代理對象的生成、InitializingBean 與 @PostConstruct 的執行時機,全都建立在這條鏈路之上。也正因如此,AOP 之後拿到的往往已不是原始對象而是代理對象——若忽視生命週期順序,很容易在「為什麼注入進來的是代理類」這類問題上繞遠路。
實踐提醒:兩個方法都必須返回對象(通常是傳入的 bean 本身),返回 null 會導致後續流程出錯;同時後置處理器會作用于容器內所有 Bean,判斷類型時務必做好 instanceof 或 beanName 過濾,避免污染無關 Bean。