Spring AOP - 在没有XML配置的情况下切面不起作用

5

我想在服务中运行获取消息方法之前运行切面。我不想使用xml配置,所以我添加了(希望)必要的注释。但是,当我运行我的应用程序时,切面不起作用,什么也没有发生。您能解释一下为什么吗?

服务

public interface Service {
  void getMessage();
}

服务实现

import org.springframework.stereotype.Component;

@Service
public class ServiceImpl implements Service {
  public void getMessage() {
    System.out.println("Hello world");
  }
}

方面

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

    @Before("execution(* com.example.aop.Service.getMessage())")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("AOP is working!!!");
    }
}

运行

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan("com.example")
public class AopApplication {

    public static void main(String[] args) {
        final ConfigurableApplicationContext run = SpringApplication.run(AopApplication.class, args);
        final Service bean = run.getBean(ServiceImpl.class);
        bean.getMessage();
    }
}

输出 仅为Hello world


请尝试使用 getBean(Service.class) - M. Prokhorov
仍然无法工作...这是简单的多态性。也许我使用了错误的注释? - MatWdo
方面不应该是 @Before("execution(* com.example.aop.ServiceImpl.getMessage())") 吗?请参见此处 https://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/。 - best wishes
你到底是什么意思?我有相同的@Before值和自己的路径... - MatWdo
2个回答

1

很可能需要在LoggingAspect类上添加@Component注释。


0

我认为切入点表达式语法应该是这样的:

@Before("execution(void com.aop.service.Service+.getMessage(..))")

+ 用于将切入点应用于子类型(您也可以用 * 替换 void)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接