Spring AOP - 方面在没有 xml 配置的情况下无法工作

Spring AOP - aspect not working without xml configuration

我的意图是运行服务中获取消息方法之前的方面。我不想使用 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

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

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

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

可能,您必须将 @Component 注释添加到 LoggingAspect class。