arakoodev / FlySpring

Developer-friendly Spring Boot flavor. Supercharged cli "flyfly" to make you fall in love with Java again
MIT License
7 stars 7 forks source link

please provide conditional load directory for flyspring #53

Open sandys opened 1 year ago

sandys commented 1 year ago

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:

  1. Create a custom annotation for your REST controllers:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomRestController {
}
  1. Annotate your REST controllers with the @CustomRestController annotation:
@CustomRestController
public class ApiController {
    // Your REST controller code
}
  1. Create a custom BeanFactoryPostProcessor to 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());
        }
    }
}
  1. 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.