Spring - Intercepting bean creation and injecting custom proxy

后端 未结 4 1617
孤独总比滥情好
孤独总比滥情好 2021-02-13 16:07

I have a @Controller with @Autowired fields and handler methods that I want to annotate with custom annotations.

For example,

         


        
4条回答
  •  醉酒成梦
    2021-02-13 16:53

    I think that not, but I supose that you could autowire the proxy after creating it.

    public class MyProcessor extends InstantiationAwareBeanPostProcessorAdapter
        implements BeanFactoryAware {
    
        private AutowireCapableBeanFactory beanFactory;
    
         @Override
            public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
                // This is where I thought I would do it, but it then skips setting fields alltogether
                if (beanClass.isAnnotationPresent(Controller.class)) {
                    Object proxy = Enhancer.create(beanClass, new MyInterceptor());
                    // autowire
                    beanFactory.autowireBean(proxy);
    
                    return proxy;
                }
                return null;
            }
    
        @Override
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            this.beanFactory = (AutowireCapableBeanFactory) beanFactory;
    
        }
    
    }
    

    Other alternative is to create a Spring AOP Proxy (using ProxyFactory) in postProcessAfterInitialization method. For this way AbstractAutoProxyCreator could be useful. See BeanNameAutoProxyCreator as sample. But imho, an annotation pointcut (Nicholas answer) do the same and is simpler.

提交回复
热议问题