ENVIRONMENT:
Java 8
Srping Framework 5
SITUATION: I need to change in Runtime @GetMapping annotation attributes values.
TASK: I have my controller and durring runtime I need to change value attribute from value = {"/**"} to value = {"/method1", "/method2"}
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping(value = {"/**"}, produces = {"application/json", "text/csv"})
public ResponseEntity<?> query(HttpServletRequest request, @RequestParam Map<String, String> params) {
..........
}
ACTION: I added custom bean post processor and via reflection tried to change the value field of @GetMappg annotation.
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MyController) {
Method[] methods = bean.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
GetMapping currentAnnotation = AnnotationUtils.findAnnotation(methods[i], GetMapping.class);
if (Objects.nonNull(currentAnnotation)) {
LOGGER.debug("GetMapping annotation before:" + currentAnnotation);
try {
Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(currentAnnotation);
annotationAttributes.put("value", new String [] {"/method1", "/method2"});
AnnotationAttributes attributes = new AnnotationAttributes(annotationAttributes);
AnnotationUtils.postProcessAnnotationAttributes(currentAnnotation, attributes, true);
LOGGER.debug("GetMapping annotation after:" + currentAnnotation);
} catch (Exception e) {
LOGGER.error("" + e);
}
}
}
}
QUESTION: I want to see my changes for value attribute in my current annotation.
ADDITIONAL INFORMATION: As a example for Field we can call
ReflectionUtils.setField(Field field, Object target, Object value);
and will saw our changes for that field.
Aucun commentaire:
Enregistrer un commentaire