A few days ago I encountered a problem AOP internal call does not take effect, and the Internet to find some way
1, using @EnableAspectJAutoProxy (exposeProxy = true) annotation
Then call AopContext.currentProxy () method to obtain the current proxy object calls need to use
2, to achieve BeanPostProcessor interface, override postProcessAfterInitialization method, an object in the initialization of the need to use manual injection
The first method I tried did not work background will complain, probably meaning set exposeProxy = true but I've set up
Analyze the reasons may be the method I use a timer to call and AopContext.currentProxy () is using the current proxy ThreadLocal stored thread context may be due to inconsistent get less than single-agent signing.
The second method is easy to use code that attach easily look after themselves,
@Configuration public class InjectBeanSelfProcessor the implements the BeanPostProcessor, ApplicationContextAware { Private ApplicationContext applicationContext; @Override public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException { // if not MyService Bean skip IF (! (Bean instanceof MyService)) { return bean; } the MyService-Service = (the MyService) the bean; // if the current object is a proxy object AOP, direct injection IF (AopUtils.isAopProxy (the bean)) { service.setSelf (the bean); } the else { // if the current object does not AOP proxy, proxy object is acquired by context.getBean (beanName) and injected // this mode is not suitable for solving prototype Bean proxy objects injection service.setSelf (to applicationContext.getBean (the beanName)); } return the bean; } @Override public void setApplicationContext (the ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
// If there are multiple classes require internal call can use the interface definition // then implement an interface on the line public class {the MyService the MyService proxySelf; public void setSelf (Object proxyBean) { this.proxySelf = (the MyService) proxyBean; } }