A custom implementation of org.springframework.format.Formatter is a valid approach for this use case. Thus, Spring itself implements formatting for dates, currencies, number styles, etc.
Steps:
Announcement Announcement: Decrypt :
import java.lang.annotation.*; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) public @interface Decrypt { }
Declare AnnotationFormatterFactory , which uses the new annotation:
import org.springframework.context.support.EmbeddedValueResolutionSupport; import org.springframework.format.AnnotationFormatterFactory; import org.springframework.format.Formatter; import org.springframework.format.Parser; import org.springframework.format.Printer; import java.text.ParseException; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Set; public class DecryptAnnotationFormatterFactory extends EmbeddedValueResolutionSupport implements AnnotationFormatterFactory<Decrypt> { @Override public Set<Class<?>> getFieldTypes() { Set<Class<?>> fieldTypes = new HashSet<>(); fieldTypes.add(String.class); return Collections.unmodifiableSet(fieldTypes); } @Override public Printer<String> getPrinter(Decrypt annotation, Class<?> fieldType) { return configureFormatterFrom(annotation); } @Override public Parser<String> getParser(Decrypt annotation, Class<?> fieldType) { return configureFormatterFrom(annotation); } private Formatter<String> configureFormatterFrom(Decrypt annotation) {
Register this factory formatter with your web context:
import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfigurer extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { super.addFormatters(registry); registry.addFormatterForFieldAnnotation(new DecryptAnnotationFormatterFactory()); } }
What is it.
Using the above, all uses of @RequestParam that qualify with @Decrypt will be passed through the parse() method declared in DecryptAnnotationFormatterFactory so you can implement your decryption call there.
To prove this, the following tests are performed:
@RunWith(SpringRunner.class) @WebMvcTest(controllers = YourController.class) public class YourControllerTest { @Autowired private MockMvc mockMvc; @Test public void theSecretRequestParameterWillBeConverted() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/customer?secret=abcdef")).andExpect(status().isOk()).andReturn();
source share