Chao
Chao

Reputation: 2051

Spring AOP - enable @Aspect programmatically

I have an aspect

@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());
        }
    }

}

I enabled it by adding it to the config class

@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;
    }
}

It works fine, butif I register this bean by adding it to beanFactory programmatically, the @Aspect annotation is not working.

@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");
        }
    }
}

any suggestions? Thanks in advance.

Upvotes: 0

Views: 1814

Answers (1)

wolf J
wolf J

Reputation: 11

Yes, your code does not work!
So, just change it like this:

Object proxyObject = beanFactory.initializeBean(broker, entry.getKey() + ".broker");
beanFactory.registerSingleton(entry.getKey() + ".broker", proxyObject);

哈哈!It works now!

Upvotes: 1

Related Questions