Я создаю простой проект для изучения aspectj.Неверный аспект в junit
Это из аспекта в действии 2-го, и идея очень проста ---- MessageCommunicator
будет отвечать за доставку сообщения, и это основная бизнес-логика. Между тем, Authenticator
будет отвечать за аутентификацию и будет соткано как заявлено SecurityAspect
.
Хотя очень просто видеть в журнале, что аспект работает. Тем не менее, я хочу, чтобы он работал в случае с junit.
В моем проекте я использую maven 3.0.4 с aspectj 1.7.3 и aspect-maven-plugin 1.5.
Теперь проблема заключается в том, что предупреждение возникает при компиляции тестового примера. Как следствие, аспекты в тестовом пакете не работают. Однако, если вы напишете основной класс в исходном пакете и запустите его, будет рассмотрен аспект в исходном пакете.
предупреждающее сообщение во время сборки:
[INFO] --- aspectj-maven-plugin:1.5:test-compile (test-compile_with_aspectj) @ aspectj --- [WARNING] advice defined in org.javen.study.aspectj.c02.aspects.MockAuthenticationAspect has not been applied [Xlint:adviceDidNotMatch] [WARNING] advice defined in org.javen.study.aspectj.c02.aspects.SecurityAspect has not been applied [Xlint:adviceDidNotMatch] [WARNING] advice defined in org.javen.study.aspectj.c02.aspects.TrackingAspect has not been applied [Xlint:adviceDidNotMatch]
Я также приложить все соответствующий исходный код ниже: MessageCommunicator
, который отвечает за основной бизнес:
package org.javen.study.aspectj.c02;
public class MessageCommunicator {
public void deliver(String message) {
System.out.println(message);
}
public void deliver(String person, String message) {
System.out.println(person + ", " + message);
}
}
Простой вариант проверки подлинности, который будет выполнять аутентификацию:
public class Authenticator {
public void authenticate() {
System.out.println("authenticated");
}
}
SecurityAspect
который посоветует на MessageCommunicator
:
package org.javen.study.aspectj.c02.aspects;
import org.javen.study.aspectj.c02.Authenticator;
public aspect SecurityAspect {
private Authenticator authenticator = new Authenticator();
declare warning
: call(void Authenticator.authenticate())
&& !within(SecurityAspect)
: "Authentication should be performed only by SecurityAspect";
pointcut secureAccess() : execution(* org.javen.study.aspectj.c02.MessageCommunicator.deliver(..));
before() : secureAccess() {
System.out.println("Checking and authenticating user");
authenticator.authenticate();
}
}
MockAuthenticationAspect
в тестовом пакете посоветовать аутентификатор, чтобы ввести некоторые проверки логики (нет необходимости смотреть на консультации подробно, реализация рекомендации проблематично):
package org.javen.study.aspectj.c02.aspects;
import org.javen.study.aspectj.c02.Authenticator;
public aspect MockAuthenticationAspect {
declare parents: Authenticator implements Callable;
private boolean Callable.isCalled;
public void Callable.call() {
isCalled = true;
}
public boolean Callable.isCalled() {
return isCalled;
}
Object around(Callable accessTracked) : execution(* Authenticator.authenticate(..))
&& !execution(* Callable.*(..))
&& this(accessTracked) {
accessTracked.call();
return null;
}
private static interface Callable {
}
}
пОМ всего проекта:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.javen.study</groupId>
<artifactId>aspectj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<aspectj.version>1.7.3</aspectj.version>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.5</version>
<configuration>
<complianceLevel>1.6</complianceLevel>
<includes>
<include>**/*.java</include>
<include>**/*.aj</include>
</includes>
</configuration>
<executions>
<execution>
<id>compile_with_aspectj</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile_with_aspectj</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Когда сборки с командой «MVN чистой Insta ll ", тексты предупреждений будут напечатаны, и совет тестового пакета не будет работать. Однако, если вы проверите с AJDT в eclipse, все pointcut и советы работают.
Не мог бы кто-нибудь мне помочь? Большое спасибо.