原理圖
https://www.processon.com/apps/5d1c16dde4b076f4fd3f5c40
package com.beanPostProcessor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.core.PriorityOrdered; import org.springframework.stereotype.Component; @Component public class Lwj_BeanPostPocessor implements BeanPostProcessor, PriorityOrdered { //實現PriorityOrdered,實現getOrder方法返回一個數值越小越靠前執行 @Override public int getOrder() { return 102; } //初始化之前植入的切面方法 @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if("wjwTest".equals(beanName)){ System.out.println("Lwj_BeanPostPocessor之前的方法"); } return bean; } //初始化之後植入的切面方法 @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if("wjwTest".equals(beanName)){ System.out.println("Lwj_BeanPostPocessor之後的方法"); } return bean; } }
此方式是spring提供的擴展點之一,spring中一共存在五種擴展方式。
再應用中單例(singleton)調用原型(prototype)可以使用兩種方式
Lookup方式 需要注意的是@Lookup只能註解在方法上,這個時候可以註解在一個抽象方法上。
實現ApplicationContextAware接口實現set方法,此方式是重新創建一個beanFactory然後從工廠中再獲取一個bean此時這個newBean與原工廠中的oldBean類型一致但在LVM的堆中不屬於同一個