0

Created Custom annotation and add annotation at method level and pass value to Spring-Aspect.

springboot: application.properties spring.event.type=TEST

Output: PreHook Value|${spring.event.type}

I am expecting : TEST

Can someone please help how to populate value from properties file and inject to annotation.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PreHook {
String eventType();
}

@Aspect
@Component
public class ValidationAOP {

@Before("@annotation(com.example.demo.annotation.PreHook)")
public void doAccessCheck(JoinPoint call) {
    System.out.println("ValidationAOP.doAccessCheck");

    MethodSignature signature = (MethodSignature) call.getSignature();
    Method method = signature.getMethod();

    PreHook preHook = method.getAnnotation(PreHook.class);
    System.out.println("PreHook Value|" + preHook.eventType());
}
}`

@RestController
public class AddController {

@GetMapping("/")
@PreHook(eventType = "${spring.event.type}")
public String test() {
    System.out.println("Testcontroller");
    return "Welcome Home";
}
}
  • You have to add SPEL processing to you annotation to evaluate that expression. You should not expect Spring to handle everything for you magicaly out of the box. – Antoniossss Nov 28 '22 at 07:17

2 Answers2

0

Please refer below link for details. you are just few steps away.

Use property file in Spring Test

Saurabh
  • 13
  • 2
0

You have to add SPEL processing to you annotation to evaluate that expression. You should not expect Spring to handle everything for you magicaly out of the box.

public void doAccessCheck(JoinPoint call) {
    ///(....)
    PreHook preHook = method.getAnnotation(PreHook.class);

    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(preHook.eventType());
    String parsedType= (String) exp.getValue();
    System.out.println("PreHook Value|" + parsedType);

}
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • This is a nice workaround. However, I also want to explain why the OP's naive approach does not work: **Java annotation values have to be constants** which are evaluated at compile time. Therefore, if such a constant contains an expression which is to be parsed and evaluated dynamically, the JVM knows nothing about it, which explains why either you as a developer or the framework you use (Spring or whatever) need to take care of it. – kriegaex Nov 28 '22 at 08:21