Using @Import for Modular Spring Boot Applications
This article explains how to modularize a Spring Boot monolith by splitting it into Maven modules, leveraging @ComponentScan, @Import, custom annotations, ImportSelector, ImportBeanDefinitionRegistrar, and conditional loading to dynamically include or exclude functionality at runtime.
When developing Spring Boot back‑end applications, a four‑layer architecture works well for small monoliths, but as features grow the project becomes bulky and hard to maintain.
To keep a single‑module project manageable, you can split it into multiple Maven modules, each representing a functional area, and import those modules into the main module without turning the whole system into a distributed micro‑service architecture.
The entry point for component scanning is defined by @SpringBootApplication (which includes @ComponentScan ). By default the scan starts from the package of the main class and its sub‑packages.
Using @Import on a configuration class allows you to bring another module’s configuration class (often annotated with @ComponentScan ) into the IoC container, so its beans become available in the main application.
You can wrap this import logic in a custom annotation, e.g., @EnableFunctionOne , which itself is meta‑annotated with @Import . Applying the custom annotation to the main class enables or disables the corresponding module.
For more flexible imports, implement ImportSelector . In the selectImports method you return fully‑qualified class names (e.g., com.gitee.swsk33.functionone.FunctionOneApplication ) that Spring will import at runtime.
Alternatively, implement ImportBeanDefinitionRegistrar to programmatically register bean definitions. In the registerBeanDefinitions method you create GenericBeanDefinition instances for the target classes and register them with the provided BeanDefinitionRegistry .
Conditional loading can be added with @ConditionalOnProperty on the import configuration, allowing you to enable or disable a module via a property such as com.gitee.swsk33.function-one.enabled=true in application.properties .
Overall, @Import and its related extension points provide a powerful way to achieve modular, configurable Spring Boot applications while keeping the codebase clean and maintainable.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.