I have written a jar which contains an Aspect, Please find the classes and xml below:-
package com.foo.bar;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface APILock {
int lockAtMostFor() ;
int lockAtLeastFor() default 0;
}
package com.foo.bar.aspect;
@Aspect
@Component
@Slf4j
public class APILockAspect {
@Around("@annotation(com.foo.bar.APILock)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Inside Aspect");
joinPoint.proceed();
}
}
spring-boot-aop dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
along with other spring-webflux starters
And I use this jar as an dependency in another boot application, please see my boot application below:-
package com.bla.application;
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@SpringBootApplication
@ComponentScan(basePackages = {"com.foo.bar","com.bla"})
public class ReactiveApplication {
public static void main(String[] args) {
SpringApplication.run(ReactiveApplication.class, args);
System.out.println("--------STARTED------------");
}
}
package com.bla.service;
@Service
public class CityService {
@Autowired
private CityRepository cityRepository;
public Flux<City> getAllEmployees() {
return cityRepository.findAll();
}
@APILock(lockAtLeastFor = 30,lockAtMostFor = 60)
public Mono<City> updateCity( City city, APILockKey key) {
try {
return cityRepository.save(city);
}catch (Exception e) {
return Mono.error(e);
}
}
}
But when I hit my request for updateCity
, it's not executing my aspect(APILockAspect) but directly executing the service logic, can anyone help me find what I am doing wrong?
It looks you've done everything right, but still it doesn't work, so please check the following (it should have been written as a comment, not as an answer, but its too much text, so its still better than nothing :) ):
Make sure that the jar with an aspect is not a spring boot application by itself (go to target folder and see that the artifact created out of this jar by maven/gradle does not include stuff like BOOT-INF
folder inside. This is because you can't make one spring boot app depend on another.
Make sure that the aspect is recognized by spring during the startup: Add a no-op constructor and log something from the aspect / place a breakpoint.