简体   繁体   English

如何创建Spring命名Bean的多个实例?

[英]How To Create Several Instances Of Spring Named Bean?

lets start with code : 让我们从代码开始:

@Named
public class Dashlet implements GlobalDashlet {
    private DashletContent dashletContent;
    //OTHER STUFF
}

How can i create an other instance of Dashlet Class? 如何创建Dashlet类的另一个实例? say i have a method in this class like : 说我在此类中有一个方法,例如:

public GlobalDashlet getInstance(DashletContent content) {
        Dashlet dashlet =  new Dashlet();
        dashlet.setDashletContent(dashletContent);
    return dashlet;
}

as you know the above method wont work because managed beans should be instantiated by spring or else it is not a managed bean. 如您所知,上述方法将不起作用,因为托管bean应该在spring之前实例化,否则它不是托管bean。 so is it possible to reproduce a managed bean? 因此可以重现托管bean吗?

one more question, is it possible to attach e bean to spring bean container (so that spring can manage it) ? 还有一个问题,是否可以将e bean附加到spring bean容器(以便spring可以管理它)? like merge functionality in hibernate? 像休眠中的合并功能?

If you want to attach to spring framework, you can use the prototype scope: 如果要附加到spring框架,则可以使用原型范围:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-prototype http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-prototype

Example xml configuration: xml配置示例:

<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>

Example javaConf configuration: 示例javaConf配置:

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}

You want your Dashlet bean to be prototype scoped. 您希望您的Dashlet bean被原型限制。

Then, you can get new instances of the bean by making your consumer bean ApplicationContextAware and then use the applicationContext.getBean(..) to get bean instances when required. 然后,可以通过使您的使用者bean ApplicationContextAware获得bean的新实例,然后在需要时使用applicationContext.getBean(..)获取bean实例。

Another way to achieve this would be using the @Configuration annotation as described here . 实现这一目标的另一种方法将使用@Configuration注释描述在这里

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

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