I'm familiar with Springs Java based configuration options, including the usage of @Component
and @Configuration
in conjunction with @Bean
annotations to register Spring beans.
However, when converting a decent size project to Spring, it can be very labor intensive to systematically touch all classes in the project and update with @Configuration
@Bean
s or annotating each class with @Component
. We have a large Groovy project to be converted and I would like to simplify the process.
My question: Is there a facility provided in Spring that allows you to tell Spring to auto-configure all valid bean candidate classes within a specific package?
If not, what other options are available?
I'd do pretty much the same thing that Roman did, only I'd do it at build time, not at runtime, using code generation. The rationale here is that I strongly prefer magic to happen at build time to magic that happens at deploy time.
In the simplest version, write a main method that scans the package (instead of reflections api, I'm using Guava's ClassPath scanner) and creates a
@Bean
method for every class it finds.For the Code generation, I'd use JCodeModel:
At the risk of sounding primitive, why not just do a simple find and replace in your IDE (e.g. search for "public class" in a package and replace with "@Component public class") ? That should be much quicker than trying to do anything programatically.
You can try to use your own BeanDefinitionRegistryPostProcessor
See sample project at https://github.com/sandarkin/so-q37548350
ClassPathBeanDefinitionScanner
is all you need.You can pass custom logic in include filter if you want. In current version every class in the provided package will be included as a bean.
But it is impossible to build a right dependency structure on your classes automagically, it really depends on the scope you want. You need to do it by your hands.