Ultimately what I want to do is dynamically create RestControllers in my Spring project based on some custom bean types. During post processing (via BeanFactoryPostProcessor), I look for particular bean definitions and programmatically generate RestController bean definition for each one. However, I want to set the base path for each of the RestController using the RequestMapping annotation, but I'm not sure how to do this. The AnnotatedBeanDefinition has introspection mechanisms, but I want to be able to specify the value of the RequestMapping annotation. Is there a way to achieve this?
I'm trying to achieve something similar to what Spring Data REST does for Repository: dynamically create a REST endpoint to expose CRUD operations. However, I have slightly different use case that does not fit Spring Data REST's framework.
I have a template controller that exposes some endpoints:
@RestController
class TemplateController<T> {
private DataService<T> service;
TemplateController(DataService<T> service) {
this.service = service;
}
@GetMapping("/data")
T getData() {}
}
Using the BeanFactoryPostProcessor, I scan for all BeanDefinitions for type DataService. What I'm hoping to do next is to register a BeanDefinition for the TemplateController that refers to the specific DataService. However, I want to be able to set different RequestMappings for each of the dynamically defined TemplateControllers.
@Configuration
class Configuration {
@Bean
BeanFactoryPostProcessor postProcess() {
return beanFactory -> {
//assume a collection of BeanDefinitions for DataService
dataServiceDefs.forEach {def ->
var controllerDef = defineController(def);
//then insert RequestMapping here hopefully
asRegistry(beanFactory).register(deriveName(def), controllerDef);
}
}
}
}
Note: The solution suggested in the proposed duplicated question does not address the issue about programmatically adding annotations, or if that's even possible.