This repository was archived by the owner on Jun 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
This repository was archived by the owner on Jun 30, 2023. It is now read-only.
please provide conditional load directory for flyspring #53
Copy link
Copy link
Open
Description
i have a spring boot application with thousands of rest controllers. i want to prevent these rest controllers to load when spring boot starts.
i want to be able to load them explicitly by importing the rest controller and initializing it in the main function.
please write code and configuration to make this possible
you can use the following approach to selectively enable your REST controllers:
- Create a custom annotation for your REST controllers:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomRestController {
}- Annotate your REST controllers with the
@CustomRestControllerannotation:
@CustomRestController
public class ApiController {
// Your REST controller code
}- Create a custom
BeanFactoryPostProcessorto register your REST controllers as beans:
public class CustomRestControllerRegistrar implements BeanFactoryPostProcessor {
private final List<Class<?>> controllers;
public CustomRestControllerRegistrar(List<Class<?>> controllers) {
this.controllers = controllers;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (Class<?> controller : controllers) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(controller);
beanFactory.registerBeanDefinition(controller.getSimpleName(), beanDefinitionBuilder.getBeanDefinition());
}
}
}- In your main function, initialize the desired REST controllers and register them using the
CustomRestControllerRegistrar:
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringBootApplication.class);
// Initialize the desired REST controllers
List<Class<?>> controllers = new ArrayList<>();
controllers.add(ApiController.class);
// Add more controllers as needed
// Register the REST controllers as beans
app.addInitializers(applicationContext -> {
applicationContext.addBeanFactoryPostProcessor(new CustomRestControllerRegistrar(controllers));
});
app.run(args);
}
}Now, only the REST controllers that you explicitly initialize and add to the controllers list in the main function will be loaded when the Spring Boot application starts.
Metadata
Metadata
Assignees
Labels
No labels