Roman
Roman

Reputation: 66156

Using prototype beans defined in a different java-based Spring config file

Assume we have two spring config files: ConfigA.java and ConfigB.java.

Here's how ConfigA.java may look like:

@Configuration
class ConfigA {

  @Scope("prototype") 
  @Bean public Foo fooPrototype() {
      return new Foo(params);
  }
}

And now I want to inject a few instances of Foo to a number of singleton-scoped beans declared in ConfigB.java:

@Configuration
@Import(ConfigA.class)
class ConfigB {

  @Bean public Bar bar() {
      return new Bar(*** how to inject Foo instance here? ***);
  }

  @Bean public Buzz buzz() {
      return new Buzz(*** how to inject Foo instance here? ***);
  }    
}

If I had a single configuration file, I would simply replace the blocks enclosed in asterisks with fooPrototype().

But, how to inject different Foo instances to bar() and buzz() beans provided fooPrototype() is declared in a different configuration file?

Upvotes: 2

Views: 152

Answers (2)

Seelenvirtuose
Seelenvirtuose

Reputation: 20618

This looks similar to the example in the Spring documentation §5.12.5 Composing Java-based configurations.

This same page gives a solution: You can autowire the configuration beans.

@Configuration
@Import(ConfigA.class)
class ConfigB {

    @Autowired ConfigA configA;

    @Bean public Bar bar() {
        return new Bar(configA.fooPrototype());
    }

    @Bean public Buzz buzz() {
        return new Buzz(configA.fooPrototype());
    }
}

Upvotes: 2

Jonathan
Jonathan

Reputation: 20375

Can't you just pass fooPrototype as a method arg? E.g.:

@Bean public Bar bar(Foo fooPrototype) {
    return new Bar(fooPrototype);
}

@Bean public Buzz buzz(Foo fooPrototype) {
    return new Buzz(fooPrototype);
} 

Upvotes: 1

Related Questions