弹簧AOP-没有XML配置,无法正常工作



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

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

我相信尖端表达式语法应该是这样的:

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

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

最新更新