简体   繁体   中英

Inject list of initialized beans

I need to inject list of already initialized beans into some another one.

I have class with definitions of some lazy beans which are used depending on environment - like on server 1 only impl1 and impl2 will be used and on server 2 impl3 and impl1

@Component
class Definitions {
    @Bean
    @Lazy
    public A impl1() { /* ... */ }

    @Bean
    @Lazy
    public A impl2() { /* ... */ }

    @Bean
    @Lazy
    public A impl3() { /* ... */ }
}

And I have some monitoring bean which don't know anything about environment and just collects all those A beans exposing some health information for actuator:

@Component
class Monitoring implements HealthIndicator {
    @Autowired
    private List<A> monitored;
}

Problem is that spring wires all beans into monitored even if they were not initialized before (which crashes the whole thing, cause there is no suitable environment). And I need to somehow explain to spring that I only need already initialized beans - something like @AutowireOnlyThoseLazyBeansWhichAlreadyBeenUsedSomewhereElse

PS I know that I can use dirty hack and declare a list property inside Definitions , fill it in bean factory methods and register another one bean with reference to that list but it is too dirty.

解决方案是通过监视BeanPostProcessor某种特定类型的bean,并将动态bean与并发映射中的所有跟踪bean注册到上下文中,来编写类似于OSGi的自定义“ ServiceTracker”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM