You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将独立AspectJ Java项目的切面织入Spring Boot应用

Spring Boot复用独立切面项目的落地实现方案

这里提供两种生产环境验证过的实现方式,优先推荐Spring AOP集成方案,接入成本极低,覆盖90%以上常规业务场景。


方案1:Spring AOP集成(推荐)

步骤1:改造独立切面Test项目

  • 给Test项目的pom.xml新增Spring Context依赖,scope设为provided避免版本冲突:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>和目标Spring Boot版本匹配即可</version>
    <scope>provided</scope>
</dependency>
  • 给切面实现类添加@Component注解,方便Spring容器识别:
@Aspect
@Component // 新增注解
public class SecuredMethodAspect {
    // 原有逻辑不变
}
  • 新增Spring Boot自动配置类,实现引入依赖即可自动加载切面,无需手动扫包:
@Configuration
@ComponentScan(basePackages = "切面类所在的完整包路径")
public class SecuredAspectAutoConfiguration {
}
  • 在Test项目的resources/META-INF/spring目录下新建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,写入自动配置类的全限定名,Spring Boot 2.7+版本原生支持该自动装配规则。
  • 执行mvn install将Test项目打到本地Maven仓库,若团队共用可deploy到私有Maven仓库。

步骤2:Spring Boot项目接入

  • 引入Test项目依赖:
<dependency>
    <groupId>aspect</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
  • 引入Spring AOP Starter依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • 无需额外配置,直接在需要拦截的方法上添加@Secured注解即可生效:
@Secured(isLocked = true)
public void yourBusinessMethod() {
    // 业务逻辑
}

注意:该方案仅支持拦截Spring容器管理的Bean的public方法,同类内方法调用不会触发切面,如有此类需求请用方案2。


方案2:原生AspectJ编译期织入(适用于全类拦截场景)

如果需要拦截非Spring管理的类、私有方法、同类内调用的方法,可使用该方案。

步骤1:Test项目无需额外改造,直接打包上传到Maven仓库即可

步骤2:Spring Boot项目改造

  • 引入Test项目和aspectjrt依赖
  • 在Spring Boot项目的pom.xml中添加aspectj编译插件,指定织入Test项目中的切面:
<plugin>
    <groupId>com.nickwongdev</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.12.6</version>
    <configuration>
        <source>11</source>
        <target>11</target>
        <complianceLevel>11</complianceLevel>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>aspect</groupId>
                <artifactId>test</artifactId>
            </aspectLibrary>
        </aspectLibraries>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>
  • 编译Spring Boot项目时会自动将切面逻辑织入所有匹配的类中,不受Spring容器限制。

内容的提问来源于stack exchange,提问作者ak219

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 09:15:07