如何使用基于java的注释启用<aop:aspectj-autoproxy> </aop:aspectj-autoproxy>

时间:2012-05-04 12:30:45

标签: java spring spring-aop

我正在尝试在没有任何XML的情况下设置Spring AOP。 我想在一个类中启用<aop:aspectj-autoproxy>@Configuration注释。

这是在XML文件中定义的方式:

<aop:aspectj-autoproxy>
<aop:include name="msgHandlingAspect" />
</aop:aspectj-autoproxy>

我尝试使用@Configuration@EnableAspectJAutoProxy为我的课程添加注释 但什么都没发生。

2 个答案:

答案 0 :(得分:46)

您是否在同一@Configuration课程中创建了一个方面bean? 这是the docs建议的内容:

 @Configuration
 @EnableAspectJAutoProxy
 public class AppConfig {
     @Bean
     public FooService fooService() {
         return new FooService();
     }

     @Bean // the Aspect itself must also be a Bean
     public MyAspect myAspect() {
         return new MyAspect();
     }
 }

答案 1 :(得分:0)

我使用了公认的答案解决方案,但是遇到了意外问题,直到将这个参数添加到配置中之前,我才明白。

@EnableAspectJAutoProxy(proxyTargetClass = true)

如果在@Controller中使用注释,则需要以这种方式进行配置

请记住,如果您使用的是Java 8,则需要使用高于1.8.X的AspectJ版本。

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AppConfig {

    @Bean
    public AccessLoggerAspect accessLoggerAspect() {
        return new AccessLoggerAspect();
    }

}