Home > Software design >  Annotation value not reading from springboot properties.file
Annotation value not reading from springboot properties.file

Time:11-28

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";
}
}

CodePudding user response:

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);

}

CodePudding user response:

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

Use property file in Spring Test

  • Related