简体   繁体   中英

java annotation to modify value

I have a web application with spring, one rest endpoint receives a value encrypted like this:

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public resp welcome(
    @RequestHeader(name = "user") String user, 
    @Encripted @RequestHeader(name = "password") String password 

I'm creating the annotation @Encripted like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Encripted {
}

now I need to manipulate the String that got annotated and change its value, how could I override or implement to achieve this goal? I can't find example with ElementType.PARAMETER,

Lets say you created WelcomeController and Encrypted classes in com.example.controller like so,

package com.example.controller;

public class WelcomeController {
   @RequestMapping(value = "/welcome", method = RequestMethod.GET)
   public void welcome(
     @RequestHeader(name = "user") String user, 
     @Encrypted @RequestHeader(name = "password") String password 
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Encrypted {
   String value() default "";
}

In order to process the Annotation you need to create an Aspect class like so --

@Aspect
public class MyAspect {
    @Pointcut("execution(@com.example.controller.WelcomeController * *(@com.example.controller.Encrypted (*), ..)) && args(password)")
    public void encryptedMethod(String password) {}

    @Around("encryptedMethod(password)")
    public Object encryptedMethod(ProceedingJoinPoint pjp, String password) throws Throwable {
        // process the password string ...
        return pjp.proceed();
    }
}

Check more on the AOP with Spring here -- https://www.baeldung.com/spring-aop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM