前言

Spring允许使用自动代理Bean,其原理为通过BeanPostProcessor处理容器中的Bean.为当前bean查找可用的Advisor(切面).Spirng中的Advisor持有Advice,而Advice类似一种拦截器,表示对原始调用作增强。如AspectJ中的around切点的处理类图为:

AspectJAroundAdvice.png

BeanNameAutoProxyCreator

The BeanNameAutoProxyCreator class is a BeanPostProcessor that automatically creates AOP proxies for beans with names that match literal values or wildcards. The following example shows how to create a BeanNameAutoProxyCreator bean.

如何使用

  1. <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  2. <property name="beanNames" value="jdk*,onlyJdk"/>
  3. <property name="interceptorNames">
  4. <list>
  5. <value>myInterceptor</value>
  6. </list>
  7. </property>
  8. </bean>
  9. <bean id="myInterceptor" class="com.example.springboot.springbootdemo.aop.MyInterceptor"/>
  10. /**
  11. * @author xiele on 2020/7/12
  12. */
  13. public class MyInterceptor implements MethodInterceptor {
  14. @Override
  15. public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  16. return methodInvocation.proceed();
  17. }
  18. }

说明:为单个Bean创建代理
BeanNameAutoProxyCreator是一个PostBeanProcessor,容器获取单例对象时,会执行getEarlyBeanReference方法,该方法作查找容器里的Advisor,BeanNameAutoProxyCreator直接返回常量:
Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0]
表示不依赖其他Advisor.