Spring AOP建议方法不起作用。我的配置似乎没问题

时间:2017-11-10 10:02:37

标签: java spring spring-aop

我正在尝试创建一个演示AOP应用程序,但它无法正常工作。 我阅读了所有教程,并使用了@RestController,但是当我尝试使用普通的java弹簧驱动应用程序时,我无法让它工作。请查看我的文件并告诉我我的错误在哪里。

申请类

@SpringBootApplication
@ComponentScan("com.xetra.experimental")
@EnableAspectJAutoProxy
public class AoptryoutnowebApplication {

  public static void main(String[] args) {
    SpringApplication.run(AoptryoutnowebApplication.class, args);
    DefaultClassToAspectImpl defaultClassToAspectImpl = new DefaultClassToAspectImpl();
    defaultClassToAspectImpl.doStuff();
  }
}

ClassToAspect Interface

public interface ClassToAspect {
  void doStuff();
}

ClassToAspect Implementation

@Component
public class DefaultClassToAspectImpl implements ClassToAspect {
  @FooAnnotation
  public void doStuff(){
    System.out.println("DoStuff!");
  }
}

Pointcut的注释

public @interface FooAnnotation {
}

Aspect Class

@Aspect
public class FooAspect {

  @Pointcut("@annotation(FooAnnotation)")
  public void methods(){
  }

  @Before("methods()")
  public void doAspect(){
    System.out.println("FooAspect before");
  }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

  1. @EnableAspectJAutoProxy替换为@EnableAspectJAutoProxy(proxyTargetClass = false)

  2. 将切入点更改为 @Pointcut("execution (* your.package..*.*(..)) && @annotation(fooAnnotation))")

答案 1 :(得分:0)

问题是您通过new DefaultClassToAspectImpl()使用非Spring托管实例。 Spring AOP仅适用于Spring托管bean,因为默认情况下Spring AOP是基于代理的。

因此,您应该从new DefaultClassToAspectImpl()获取实例,而不是ApplicationContext。使用Spring Boot时,SpringApplication.run调用将返回ApplicationContext。在这里,您可以使用getBean方法之一来获取所需的实例。

ApplicationContext ctx = SpringApplication.run(AoptryoutnowebApplication.class, args);
ClassToAspect bean = getBean(ClassToAspect.class);
bean.doStuff();

这样你就得到了Spring管理