简体   繁体   English

原型bean Spring的旧实例

[英]old instance of prototype bean spring

my problem is i need to find existing instance of prototype bean [it is thread actually]. 我的问题是我需要找到原型bean的现有实例[实际上是线程]。 multiple instance of particular bean exists anytime of application. 任何时候应用程序都存在特定bean的多个实例。

Another master thread which manages bunch of such threads if any of thread is not completed in time . 如果一个线程没有及时完成,则另一个主线程管理一堆这样的线程。 master thread should kill them . 主线程应该杀死它们。

PrototypeBean someBean=applicationContext.getBean(PrototypeBean.class); PrototypeBean someBean = applicationContext.getBean(PrototypeBean.class);

will create another instance of bean [which i do not want]. 将创建另一个bean实例[我不想要]。 not sure how to get existing instance of bean . 不知道如何获取现有的bean实例。 is there any way spring can give me list of all instances of Bean for any class. spring有什么办法可以给我任何类的Bean所有实例的列表。

let me know if you require any more information. 让我知道您是否需要更多信息。

You could register that prototype beans in an single scoped bean after creation. 创建后,您可以在单个作用域bean中注册该原型bean。

@Scope("prototype")
@Component
public class YourPrototypeTypeBean() {
    @Autowired
    private FinderBean finderBean;

    @PostConstruct
    public void init() {
        finderBean.register(this);
    }
}

@Service
public class FinderBean {
     private Set<YourPrototypeTypeBean> allYourPrototypeTypeBeans = new HashSet<>;

     public void register(YourPrototypeTypeBean beanToRegister) {
          this.allYourPrototypeTypeBeans.add(beanToRegister)
     }
}

If you need this in an multi threaded environment, you have to synchronize the access to the set or use a thread save variant! 如果在多线程环境中需要此功能,则必须同步对集合的访问或使用线程保存变量!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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