Cześć,
Mam taką własną adnotację:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AdvancedAnnotation {
boolean disabled() default false;
}
Mam taki aspekt:
package pl.margor.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Slf4j
public class AdvancedAnnotationAspect {
@Before("@annotation(AdvancedAnnotation)")
public void advAnnotationProcess(JoinPoint jp) throws Throwable {
System.out.println("Advanced annotation aspect executed");
// TO DO:
// metoda wykonuje sie
// w jaki sposob wykonac logike w zaleznosci od wartosci pola isDisabled w adnotacji?
}
}
Użycie wygląda w ten sposób:
package pl.margor.rest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import pl.margor.aop.AdvancedAnnotation;
import pl.margor.aop.TestAnnotation;
import pl.margor.services.CustomTextProvider;
@RestController
@RequestMapping("/api/hello")
@Slf4j
@RequiredArgsConstructor
public class HelloController {
@RequestMapping(method = RequestMethod.GET, path = "another")
@AdvancedAnnotation(disabled = true)
public void another() {
logger.info("another");
}
}
Pytanie: w jaki sposób elegancko uzyskać dostęp do pól w adnotacji @AdvancedAnnotation?
Mniej więcej chcę uzyskać taki efekt (nie kompiluje się):
@Aspect
@Component
@Slf4j
public class AdvancedAnnotationAspect {
@Before("@annotation(AdvancedAnnotation)")
public void advAnnotationProcess(JoinPoint jp, AdvacedAnnotation a) throws Throwable {
System.out.println("Advanced annotation aspect executed");
if(a.disabled()) {
System.out.println("Disabled field has value true");
}
}
}
To powinno być dość proste. Idealnie byłoby uzyskać adnotacje jako parametr aspektu (widziałem takie przykłady w sieci, ale mi to nie działa).