2

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?"

jelford
  • 2,625
  • 1
  • 19
  • 33
  • Not sure if I understand, but you don't really want lazy, but don't want all beans but you need to process them all at once.. Looks a bit contradictionary to me. Looks like you are trying to hack something together with the wrong tools. For me it looks like you want to use a factory bean. – M. Deinum Jun 30 '15 at 10:00
  • I need to process all the ones that are going to get used elsewhere. They actually represent remote processes, which are expensive to bring up. Unfortunately, to talk to them requires that connections to them all be statically initialized together before they can be used by other components. – jelford Jun 30 '15 at 10:11

0 Answers0