Spring 多模块项目中的 Boot AOP 不执行 Before Advice

Spring Boot AOP in multi module project does not execute Before Advice

我正在使用 Springs AOP 迈出第一步,想从一个简单的日志记录建议开始。我的项目是一个多模块maven项目,结构如下:

父项目
|__aop
|__data
|__web

Web 模块在包 de.my.awsome.project.web.service 中有一个用户服务 class,带有 saveNewUser 方法:

@Service
public class UserService {
...
    public MdUser saveNewUser(UserModel user) {
        MdUser newUser = this.save(user);
        createGroupMembership(user, newUser);
        return newUser;
    }
}

该方法按预期工作,所以不必担心相关细节。

我现在所做的是在 aop 模块中创建以下 class:

@Component
@Aspect
public class LoggingAspect {

    Logger logger = Logger.getLogger(getClass());

    @Before("execution(public * de.my.awsome.project.web.service.UserService.saveNewUser(..))")
    public void newUserLog(JoinPoint joinpoint) {
        logger.info(joinpoint.getSignature() + " with user " + joinpoint.getArgs()[0]);
}

}

我在aop模块的pom中添加了对web模块的依赖:

<dependency>
    <groupId>de.my.awsome.project</groupId>
    <artifactId>web</artifactId>
    <version>${project.version}</version>
</dependency>

我什至写了一个 ConfigurationClasse,尽管我认为这对于 SpringBoot 来说不是必需的:

@Configuration
@ComponentScan(basePackages="de.fraport.bvd.mobisl.aop")
public class AspectsConfig {

}

预期结果是 "saveNewUser with user xyz" 之类的日志消息。但是永远不会调用日志记录方法。我错过了什么?

@Configuration - 表示此文件包含 Spring 个方面的 Bean 配置。

将 @Component 替换为 LoggingAspect 的 @Configuration。

好吧,@sankar 发布的答案也没有用,但我自己找到了解决方案。

我不得不在 web 模块 pom 中为我的 aop 模块添加一个依赖项,反之亦然。然后我将 AspectsConfig 的导入添加到 Web 模块 SpringBootApplication class 并且它起作用了。

@SpringBootApplication
@Import(value= {JPAConfig.class, AspectsConfig.class})
@EnableAspectJAutoProxy
public class WebApplication {

@Autowired
private JPAConfig config;

@Autowired
private AspectsConfig aspectConfig;

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

以下步骤对我有用 - 如果有人正在寻找解决方案,请参阅下文

  1. 将 aop 依赖添加到主父 pom.xml
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
  1. 在 aop 子模块中添加您的 Aspect 实现
   @Aspect
   @Component
   public class SampleAspect {

    @After("execution(* de.my.awsome.project.testMethod())") 
    public void logAuditActivity(JoinPoint jp) { 
     System.out.println("TESTING ****************");
     System.out.println("The method is called");

   }
  1. 在你的其他子模块(web-submodule)中添加 aspect-submodule 的依赖
    <dependency>
        <groupId>de.my.awsome.project</groupId>
        <artifactId>aop</artifactId>
    </dependency>
  1. 在您的 web 项目中包含用于组件扫描的 aop 包 例如。如果 SampleAspect 在包 de.my.awsome.project 下,则需要按以下方式添加
    @ComponentScan(basePackages = {"de.my.awsome.project", "de.my.awsome.aop" }
  1. 清理构建和 运行 应用程序