MoienGK
MoienGK

Reputation: 4654

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? 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. so is it possible to reproduce a managed bean?

one more question, is it possible to attach e bean to spring bean container (so that spring can manage it) ? like merge functionality in hibernate?

Upvotes: 1

Views: 356

Answers (2)

ajnavarro
ajnavarro

Reputation: 738

If you want to attach to spring framework, you can use the prototype scope:

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

Example xml configuration:

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

Example javaConf configuration:

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

Upvotes: 1

Varun Phadnis
Varun Phadnis

Reputation: 681

You want your Dashlet bean to be prototype scoped.

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.

Another way to achieve this would be using the @Configuration annotation as described here.

Upvotes: 0

Related Questions