I have a service that will post-process all beans of a specific type, to provide some initialization, and provide a new bean that contains some derived information from that step. The result of the post-processing is some static initialization, and a set of remote connection details (which are then used to construct other beans).
What I'd like to do, is have it only run on beans that my application context was already going to initialize - i.e. not instantiate beans that wouldn't otherwise have been created because they are annotated with @Lazy
:
@Config
public class MyPostProcessingBean {
@Bean
RemoteConnectionDetails postProcessBeans(PostProcessable... beans) {
for (PostProcessable b : bean) {
b.postProcess();
}
return ...
}
}
@Lazy
@Component
class X implements PostProcessable {
....
}
@Lazy
@Component
class Y implements PostProcessable {
}
@Bean
Foo foo(X x, RemoteConnectionDetails rcd) { ... }
My auto-wire candidate requires only an instance of X
- so I'd ideally like spring only to instantiate (and process) an X. Currently, when Spring resolves all the candidates for PostProcessable...
, it's instantiating Y
too.
I thought to use a BeanPostProcessor
for the post-processing, but need to do this initialization for all PostProcessable beans at once (there's a final step that must run after all components are ready).
A callback after the Spring context has started up is too late, since I need to inject the RemoteConnectionDetails
to finish off wiring up my context.
A @Lazy
annotation on the PostProcessable...
only delays the instantiation of the unnecessary beans; it doesn't prevent it.
Is there some supported way of constructing a bean from "All beans of a given type that are already needed by this context?"