如何通过配置禁用 AspectJ 编译

How to disable AspectJ compilation via configuration

我以 Java 风格实现方面 class:

@Aspect
public class SomeAspect {
  @Pointcut("...")
  public void somePointcut() {}

  @Around("somePointcut()")
  public ...
}

我是 AspectJ 的新手。我想知道是否有 convenient/centralized 方法来控制 Pointcut 的有效性,这样我就可以 enable/disable 它们基于某些配置 在编译时 .

运行时间你可以只使用一个if() pointcut,但我知道这不是你想要的。

对于编译时间,这取决于您构建项目的方式。我假设您使用 Maven 和 AspectJ Maven Plugin.

让我们进一步假设您在 process-sources 阶段将插件配置为 运行,如下所示:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.8</version>
    <configuration>
        <!--<showWeaveInfo>true</showWeaveInfo>-->
        <source>${java.source-target.version}</source>
        <target>${java.source-target.version}</target>
        <Xlint>ignore</Xlint>
        <complianceLevel>${java.source-target.version}</complianceLevel>
        <encoding>${project.build.sourceEncoding}</encoding>
        <!--<verbose>true</verbose>-->
        <!--<warn>constructorName,packageDefaultMethod,deprecation,maskedCatchBlocks,unusedLocals,unusedArguments,unusedImport</warn>-->
    </configuration>
    <executions>
        <execution>
            <!-- IMPORTANT -->
            <phase>process-sources</phase>
            <goals>
                <goal>compile</goal>
                <goal>test-compile</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>${aspectj.version}</version>
        </dependency>
    </dependencies>
</plugin>

然后只需添加一个 Maven 配置文件 - 让我们称之为 skip-aspectj,它通过 <phase/>:

将阶段覆盖到 none
<profiles>
    <profile>
        <id>skip-aspectj</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>aspectj-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase/>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

现在,如果您 运行 您的 Maven 构建

  • 正常情况下,编译应用方面,
  • mvn -P skip-aspectj ... 它们将处于非活动状态并且整个 AspectJ Maven 执行将被跳过。