Spring AOP - 以编程方式启用@Aspect

时间:2016-10-21 09:54:46

标签: spring aop

我有一个方面

@Aspect
@Log4j2
public class AnnotationBroker {

    @AfterReturning(pointcut = " @annotation(p) ", returning = "msg")
    public void onProducerReturn(Produce p, Object msg) throws IOException {
        for (String queue : p.queue()) {
            processCallback(msg, "", queue, p.onFailure(), p.onSuccess());
        }
    }

}

我通过将其添加到配置类

来启用它
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

    @Value("${amqp.default ?:}")
    String defaultNamespace;

    @Bean
    ConnectionFactory defaultMqConnFactory() {
        return ConnectionFactoryBuilder.build(defaultNamespace);
    }

    @Bean
    AnnotationBroker broker(){
        AnnotationBroker broker = new AnnotationBroker();
        broker.setTemplate(new RabbitTemplate(defaultMqConnFactory()));
        return broker;
    }
}

它运行正常,我通过编程方式将bean注册到beanFactory来注册这个bean,@ Aspect注释不起作用。

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

    @Autowired
    ConfigurableApplicationContext ctx;

    @PostConstruct
    void broker2() throws IOException, TimeoutException {
        Map<String, RabbitTemplate> template = ctx.getBeansOfType(RabbitTemplate.class);
        ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory();
        for (Entry<String, RabbitTemplate> entry : template.entrySet()) {
            AnnotationBroker broker = new AnnotationBroker();
            broker.setTemplate(entry.getValue());
            beanFactory.registerSingleton(entry.getKey() + ".broker", broker);
            beanFactory.initializeBean(broker, entry.getKey() + ".broker");
        }
    }
}

有什么建议吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

是的,您的代码不起作用!
所以,只需改变它:

Object proxyObject = beanFactory.initializeBean(broker, entry.getKey() + ".broker");
beanFactory.registerSingleton(entry.getKey() + ".broker", proxyObject);
哈哈!它现在有效!