Spring BPP中如何優(yōu)雅的創(chuàng)建動態(tài)代理Bean詳解
v一、前言
本文章所講并沒有基于Aspectj,而是直接通過Cglib以及ProxyFactoryBean去創(chuàng)建代理Bean。通過下面的例子,可以看出Cglib方式創(chuàng)建的代理Bean和ProxyFactoryBean創(chuàng)建的代理Bean的區(qū)別。
v二、基本測試代碼
測試實(shí)體類,在BPP中創(chuàng)建BppTestDepBean類型的代理Bean。
@Component
public static class BppTestBean {
@Autowired
private BppTestDepBean depBean;
public void test1() {
depBean.testDep();
}
public void test2() {
depBean.testDep();
}
@TestMethod
public void test3() {
depBean.testDep();
}
}
@Component
public static class BppTestDepBean {
public void testDep() {
System.out.println("HEHE");
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestMethod {
}
測試類
@RunWith(SpringRunner.class)
@SpringBootTest
public class BppTest {
@Autowired
private BppTestBean bppTestBean;
@Test
public void test() {
bppTestBean.test1();
bppTestBean.test2();
bppTestBean.test3();
}
}
v三、使用Cglib創(chuàng)建代理Bean
public class ProxyBpp1 implements BeanPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyBpp1.class);
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof BppTestBean) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(bean.getClass());
//標(biāo)識Spring-generated proxies
enhancer.setInterfaces(new Class[]{SpringProxy.class});
//設(shè)置增強(qiáng)
enhancer.setCallback((MethodInterceptor) (target, method, args, methodProxy) -> {
if ("test1".equals(method.getName())) {
LOGGER.info("ProxyBpp1 開始執(zhí)行...");
Object result = methodProxy.invokeSuper(target, args);
LOGGER.info("ProxyBpp1 結(jié)束執(zhí)行...");
return result;
}
return method.invoke(target, args);
});
return enhancer.create();
}
return bean;
}
}
主要是代理 BppTestBean的test1方法。其實(shí)這種方式創(chuàng)建的代理Bean使用問題的,@Autowired字段沒有注入進(jìn)來,所以會有出現(xiàn)NPE。methodProxy.invokeSuper(target, args) ,這一行代碼是有問題的,targe是代理類對象,而真實(shí)的對象是postProcessBeforeInitialization(Object bean, String beanName) 中的bean對象,此時(shí)bean對象@Autowired字段已經(jīng)注入了。所以可以將methodProxy.invokeSuper(target, args) 修改為method.invoke(bean, args)解決無法注入@Autowired字段的問題。
v四、使用ProxyFactoryBean創(chuàng)建代理Bean
public class ProxyBpp2 implements BeanPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyBpp2.class);
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof BppTestBean) {
ProxyFactoryBean pfb = new ProxyFactoryBean();
pfb.setTarget(bean);
pfb.setAutodetectInterfaces(false);
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
advisor.addMethodName("test1");
advisor.setAdvice((MethodInterceptor) invocation -> {
LOGGER.info("ProxyBpp2 開始執(zhí)行...");
Object result = invocation.getMethod().invoke(invocation.getThis(), invocation.getArguments());
LOGGER.info("ProxyBpp2 結(jié)束執(zhí)行...");
return result;
});
pfb.addAdvisor(advisor);
return pfb.getObject();
}
return bean;
}
}
使用ProxyFactoryBean創(chuàng)建代理Bean的時(shí)候,一定要一個(gè)targe對象的。Advisor在切入的時(shí)候,會逐個(gè)執(zhí)行Advice。invocation.getThis()就是在通過ProxyFactoryBean創(chuàng)建代理Bean的時(shí)候傳入的target對象。由于target對象就是postProcessBeforeInitialization(Object bean, String beanName) 中的bean對象,所以@Autowired字段也已經(jīng)注入進(jìn)來了。
v五、@Autowired注解何時(shí)被處理
想必大家都知道@Autowired字段的處理也是通過一個(gè)BPP,不過這個(gè)BPP比我們平常使用的要高級一些,它就是InstantiationAwareBeanPostProcessor。這個(gè)BPP可以實(shí)現(xiàn)Bean的創(chuàng)建、屬性的注入和解析(比如@Autowired、@Value、@Resource等等),大家可以參考一下CommonAnnotationBeanPostProcessor(處理JSR-250相關(guān)注解),AutowiredAnnotationBeanPostProcessor(處理@Autowired、@Value、@Inject相關(guān)注解)。
InstantiationAwareBeanPostProcessor中有一個(gè)如下的方法,AutowiredAnnotationBeanPostProcessor就是覆蓋這個(gè)方法實(shí)現(xiàn)了帶有相關(guān)注解屬性的自動注入。
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
return null;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
InstantiationAwareBeanPostProcessor的postProcessProperties方法實(shí)在Spring AbstractAutowireCapableBeanFactory的populateBean方法中被調(diào)用。在AbstractAutowireCapableBeanFactory的doCreateBan中有如下代碼。
// Initialize the bean instance.
Object exposedObject = bean;#
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
也就是先進(jìn)行了Bean的屬性填充,然后進(jìn)行Bean的初始化工作。initializeBean方法中主要做了四件事。
1、invokeAwareMethods
2、applyBeanPostProcessorsBeforeInitialization
3、invokeInitMethods
4、applyBeanPostProcessorsAfterInitialization
其中2和4就是分別調(diào)用的普通的BPP中的postProcessBeforeInitialization方法和postProcessAfterInitialization方法。
這就是為什么在BPP中創(chuàng)建代理Bean的時(shí)候,對應(yīng)的目標(biāo)Bean相關(guān)的@Autowired字段已經(jīng)注入的原因了。
v六、InstantiationAwareBeanPostProcessor方式創(chuàng)建動態(tài)代理Bean
InstantiationAwareBeanPostProcessor接口中有個(gè)postProcessBeforeInstantiation方法,可以讓我們自己去實(shí)例化Bean。通過查看AbstractAutowireCapableBeanFactory,方法調(diào)用:createBean方法 -> resolveBeforeInstantiation方法 -> applyBeanPostProcessorsBeforeInstantiation方法 ->InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法,如果最終返回一個(gè)非null的實(shí)例,那么就不會再執(zhí)行doCreateBean方法。這就意味著不會有Bean屬性的填充和初始化的流程了,但是可以借助AbstractAutowireCapableBeanFactory幫助我們實(shí)現(xiàn)。
public <T> T postProcess(T object) {
if (object == null) {
return null;
}
T result;
try {
// 使用容器autowireBeanFactory標(biāo)準(zhǔn)依賴注入方法autowireBean()處理 object對象的依賴注入
this.autowireBeanFactory.autowireBean(object);
// 使用容器autowireBeanFactory標(biāo)準(zhǔn)初始化方法initializeBean()初始化對象 object
result = (T) this.autowireBeanFactory.initializeBean(object,
object.toString());
} catch (RuntimeException e) {
Class<?> type = object.getClass();
throw new RuntimeException(
"Could not postProcess " + object + " of type " + type, e);
}
return result;
}
上圖代碼,可以幫組我們實(shí)現(xiàn)非Spring容器Bean自動注入和初始化的功能。使用過Spring security同學(xué)都知道,內(nèi)部也是用了這個(gè)方式解決對象中的屬性注入問題。如果你閱讀了Spring security的源碼,你會發(fā)現(xiàn)很多對象,比如WebSecurity、ProviderManager、各個(gè)安全Filter等,這些對象的創(chuàng)建并不是通過bean定義的形式被容器發(fā)現(xiàn)和注冊進(jìn)入spring容器的,而是直接new出來的。Spring security提供的AutowireBeanFactoryObjectPostProcessor這個(gè)工具類可以使這些對象具有容器bean同樣的生命周期,也能注入相應(yīng)的依賴,從而進(jìn)入準(zhǔn)備好被使用的狀態(tài)。
使用Cglib在InstantiationAwareBeanPostProcessor 中創(chuàng)建動態(tài)代理Bean。
public class ProxyBpp3 implements InstantiationAwareBeanPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyBpp3.class);
private final AutowireCapableBeanFactory autowireBeanFactory;
ProxyBpp3(AutowireCapableBeanFactory autowireBeanFactory) {
this.autowireBeanFactory = autowireBeanFactory;
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (beanClass.equals(BppConfig.BppTestBean.class)) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(beanClass);
//標(biāo)識Spring-generated proxies
enhancer.setInterfaces(new Class[]{SpringProxy.class});
//設(shè)置增強(qiáng)
enhancer.setCallback((MethodInterceptor) (target, method, args, methodProxy) -> {
if ("test1".equals(method.getName())) {
LOGGER.info("ProxyBpp3 開始執(zhí)行...");
Object result = methodProxy.invokeSuper(target, args);
LOGGER.info("ProxyBpp3 結(jié)束執(zhí)行...");
return result;
}
return methodProxy.invokeSuper(target, args);
});
return this.postProcess(enhancer.create());
}
return null;
}
...
}
使用ProxyFactoryBean在InstantiationAwareBeanPostProcessor 中創(chuàng)建動態(tài)代理Bean。
public class ProxyBpp4 implements InstantiationAwareBeanPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyBpp4.class);
private final AutowireCapableBeanFactory autowireBeanFactory;
ProxyBpp4(AutowireCapableBeanFactory autowireBeanFactory) {
this.autowireBeanFactory = autowireBeanFactory;
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (beanClass.equals(BppConfig.BppTestBean.class)) {
ProxyFactoryBean pfb = new ProxyFactoryBean();
pfb.setTarget(this.postProcess(BeanUtils.instantiateClass(beanClass)));
pfb.setAutodetectInterfaces(false);
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
advisor.addMethodName("test1");
advisor.setAdvice((MethodInterceptor) invocation -> {
LOGGER.info("ProxyBpp4 開始執(zhí)行...");
Object result = invocation.getMethod().invoke(invocation.getThis(), invocation.getArguments());
LOGGER.info("ProxyBpp4 結(jié)束執(zhí)行...");
return result;
});
pfb.addAdvisor(advisor);
return pfb.getObject();
}
return null;
}
...
}
上述向兩種方式,注意,實(shí)例化bean后主動通過postProcess方法借助AbstractAutowireCapableBeanFactory完成對象相關(guān)屬性的注入以及對象的初始化流程。
v七、源碼分享
點(diǎn)我查看源碼,如果有任何疑問請關(guān)注公眾號后進(jìn)行咨詢。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
使用okhttp替換Feign默認(rèn)Client的操作
這篇文章主要介紹了使用okhttp替換Feign默認(rèn)Client的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
MyBatis-Plus主鍵生成策略的實(shí)現(xiàn)方法
MyBatis-Plus提供了多種主鍵生成策略,包括自增、UUID、Redis和雪花算法,本文就來介紹一下,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12
Java用split分割含一個(gè)或多個(gè)空格的字符串案例
這篇文章主要介紹了Java用split分割含一個(gè)或多個(gè)空格的字符串案例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來過來看看吧2020-09-09
詳解SpringBoot如何實(shí)現(xiàn)緩存預(yù)熱
緩存預(yù)熱是指在 Spring Boot 項(xiàng)目啟動時(shí),預(yù)先將數(shù)據(jù)加載到緩存系統(tǒng)(如 Redis)中的一種機(jī)制,下面我們就來看看SpringBoot是如何實(shí)現(xiàn)緩存預(yù)熱的吧2024-01-01
SpringBoot整合MyBatis-Plus3.1教程詳解
這篇文章主要介紹了SpringBoot整合MyBatis-Plus3.1詳細(xì)教程,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08
springboot項(xiàng)目打包并部署到Tomcat上及報(bào)錯(cuò)處理方案
這篇文章主要介紹了springboot項(xiàng)目打包并部署到Tomcat上及報(bào)錯(cuò)處理方案,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-08-08

