Internal call of Spring AOP

A few days ago, I encountered a problem that AOP internal call did not take effect. I found some methods on the Internet

1. Use @ EnableAspectJAutoProxy(exposeProxy = true) annotation

Then call AopContext.currentProxy() to get the method of calling the current proxy object.

2. Implement the BeanPostProcessor interface, rewrite the postProcessAfterInitialization method, and inject the required objects manually during initialization

 

I tried the first method, but it didn't work. The background will report an error. I set exposeProxy = true, but I have already set it

The reason for analysis may be that the method I called with the timer and AopContext.currentProxy() is the current proxy stored with ThreadLocal. It may be that the thread context is inconsistent and the single sign proxy cannot be obtained.

The second method is easy to use. It's convenient for you to see the code later,

@Configuration
public class InjectBeanSelfProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //If Bean is not MyService, skip
        if (!(bean instanceof MyService)) {
            return bean;
        }
        MyService service = (MyService) bean;
        //If the current object is an AOP proxy object, inject directly
        if (AopUtils.isAopProxy(bean)) {
            service.setSelf(bean);
        } else {
            //If the current object is not an AOP proxy, get the proxy object through context.getBean(beanName) and inject
            //This method is not suitable for proxy object injection of prototype Bean
            service.setSelf(applicationContext.getBean(beanName));
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

  

//If more than one class needs to be called internally, it can be defined by interface
//Then implement the interface 
public class MyService {

        MyService proxySelf;

        public void setSelf(Object proxyBean) {
            this.proxySelf = (MyService) proxyBean;
        }


    }

Tags: Javascript

Posted on Sun, 03 Nov 2019 12:29:23 -0800 by jambroo