原型豆弹簧的旧实例

时间:2016-02-04 20:13:00

标签: java spring multithreading

我的问题是我需要找到原型bean的现有实例[它实际上是线程]。应用程序随时存在多个特定bean实例。

另一个主线程,如果任何线程未及时完成,它将管理大量此类线程。主线程应该杀死他们。

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

将创建另一个bean实例[我不想要]。不知道如何获得现有的bean实例。有没有什么方法可以为我提供任何类的Bean的所有实例的列表。

如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

您可以在创建后在单个作用域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)
     }
}

如果您需要在多线程环境中使用此功能,则必须同步对该集的访问权限或使用线程保存变体!