两次方面打印之前使用java
我有以下@Before特性,其中如果使用自定义注释对方法进行注释, 我会进入一个打印的方面
Aspect工作正常,但打印两次,这意味着我输入Aspect两次
我可以得到一些建议,为什么这种情况会发生两次,而它应该只发生一次。谢谢
注意:这不是在Spring中,而是在纯Java中实现的
使用注释为触发方面的方法初始化
public class ClassUsingUser {
@RequestValidation(isEnabled = true)
public String doSomething(User user) {
return user.toString();
}
}
自定义注释
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RequestValidation {
boolean isEnabled() default false;
}
方面类
@Aspect
public class RequestValidationAspect {
@Before("@annotation(RequestValidation)")
public void before(JoinPoint joinPoint) {
// this is the issue where I get this printed twice.
// but expecting it to happen only once.
System.out.println("Entered Aspect!!");
}
}
只触发方法和方面的主要方法
public class SomeMainClass {
public static void main(String[] args) {
User user1 = new User();
user1.setName("Fer");
ClassUsingUser classUsingUser = new ClassUsingUser();
// based on debug, I seem to hit the following doSomething() line, go to Aspect @Before,
// come back here and go into Aspect @Before again thus printing twice.
String s = classUsingUser.doSomething(user1);
System.out.println(s);
}
}
POM文件中的依赖项和插件
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
<Xlint>ignore</Xlint>
<encoding>UTF-8 </encoding>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
共 (0) 个答案