I'm writing a library for two applications A and B. Application A defines beans with XML (without component scanning) and B uses annotations and component scanning. I want to let the library define some beans that both A and B can include. However, A and B should only include those beans when they are started in a specific Spring profile (let's say my_profile
).
The TLDR question is: is there a way to do the above without referencing my_profile
in the library and without having to explicitly exclude the library from B's component scan?
Currently, the beans in the library are defined as @Bean methods in a @Configuration class, like this:
@Configuration
open class LibraryConfig {
@Bean
open fun libraryBean() = ...
}
Now in application A, in XML, I can do this:
<beans profile="my_profile">
<bean class="com.package.LibraryConfig" />
</beans>
And that works. In application B, that uses annotations, I would like to do something like this:
@Configuration
@Profile("my_profile")
@Import(LibraryConfig::class)
open class MyProfileConfig
But since LibraryConfig is also annotated with @Configuration, it will always be found by the component scanning. So this approach to make it conditional doesn't work.
Approaches I have considered:
- Simply include the profile in a @Profile on the LibraryConfig. I don't want to do this because the library should not be aware of the profiles of its consumers.
- Explicitly exclude the LibraryConfig from the @ComponentScan of project B. The drawback here is that we have projects C D and E too, that will not use
my_profile
. I want to be able to include the library there anyway without having to explicitly exclude a part of it.
So I'm looking for a way to create a 'configuration' class that can only be explicitly included. Or any other elegant way to do the above. Can it be done?