我正在通过Spring boot AOP使用自定义注释。但是,自定义注释位于另一个项目中。我已经将该项目作为依赖项包含在我的使用应用程序中。当单独进行单元测试时,注释有效。但是,从使用中的应用程序调用时,它不起作用。我在下面提供了代码段。
请帮助。
**1st Annotation:**
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface TokenToValidate {
}
**2nd Annotation:**
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValidateToken {
}
**Aspect:**
@Aspect
@Component
public class ValidateTokenAspect {
@Before("@annotation(ValidateToken)")
public void validateToken(JoinPoint joinPoint) throws Throwable {
final String token = extractToken(joinPoint);
}
private String extractToken(JoinPoint joinPoint) {
Object[] methodArgs = joinPoint.getArgs();
Object rawToken = null;
if (methodArgs.length == 1) {
rawToken = methodArgs[0];
}
else if (methodArgs.length > 1) {
System.out.println(" ** Inside else if **");
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
Parameter[] parameters = method.getParameters();
boolean foundMarked = false;
int i = 0;
while (i < parameters.length && !foundMarked) {
final Parameter param = parameters[i];
if (param.getAnnotation(TokenToValidate.class) != null) {
rawToken = methodArgs[i];
foundMarked = true;
}
i++;
}
}
if (rawToken instanceof String) { // if rawUrl is null, instanceof returns false
return (String) rawToken;
}
// there could be some kind of logic for handling other types
return null;
}
**Consuming Application: 1. POM:**
<dependency>
<groupId>com.xxx.xxx.aspect.security</groupId>
<artifactId>SecurityUtil</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<scope>compile</scope>
</dependency>
**Aspect Config**
@Configuration
@ComponentScan({"com.XXX.XXX.aspect.security.*"})
public class AspectConfiguration {
}
**Service using the annotation**
@Service
public class SampleService {
@Bean
public ValidateTokenAspect validateAspect() {
return new ValidateTokenAspect();
}
@Autowired
private ValidateTokenAspect validateAspect;
@Bean
public SecurityUtil securityUtil() {
return new SecurityUtil();
}
@Autowired
private SecurityUtil securityUtil;
@ValidateToken
public void testAOP(@TokenToValidate String token) throws Exception{
System.out.println("** Inside test AOP 1***");
}
**Main App:**
@SpringBootApplication
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
Please help.