Struse
Struse

Reputation: 75

Using @Lookup-method in java based configuration

Annotating field/constructor is providing only one instance of the class even if the bean is configured as a prototype. But I want new instances for a particular class in a loop.

Below is my Component class:

@Component
 class Link{

    @Autowired
    private RandomClass rcobj;

    public void getFiveInstancesOfRandomClass(){
       //here I want to create  five new instances for RandomClass but I get only one by auto-wiring
    }
}

Config.class

@Configuration

class ApplicationConfig{
  @Bean
  public Link link(){ return new Link();}

  @Bean
  @scope ("prototype")
  public RandomClass randomClass(){ return new RandomClass();}
}

I looked at few examples which mostly use xml based configuration. One of the solutions is by invoking ApplicationContext but I want to solve this with lookup-method.

Upvotes: 1

Views: 840

Answers (1)

Ivan Lymar
Ivan Lymar

Reputation: 2293

To inject prototype to singleton via java config I'm using following technique:

Singleton class:

public abstract class Single
{
  abstract Proto newInstance();

  public void useBean()
  {
    System.out.println( newInstance() );
  }

}

Prototype class:

public class Proto
{

}

Context:

public class Context
{
  @Bean
  public Single single()
  {
    return new Single() {
      @Override
      Proto newInstance()
      {
        return proto();
      }
    };
  }

  @Bean
  @Scope("prototype")
  public Proto proto()
  {
    return new Proto();
  }
}

Class for testing:

  public static void main( String[] args )
  {
    ApplicationContext context = new AnnotationConfigApplicationContext( Context.class );
    Single single = context.getBean( Single.class );
    single.useBean();
    single.useBean();
  }

From output we can see that each call used different object:

test.Proto@b51256
test.Proto@1906517

p.s. I totally agree with you, we should not bind beans with applicationContext. It creates additional coupling and I believe this is not a good practice.

Upvotes: 3

Related Questions