5

I have a bean that contains two autowired instances of the same component:

@Component
public SomeBean {
    @Autowired
    private SomeOtherBean someOtherBean1;
    @Autowired
    private SomeOtherBean someOtherBean2;
    ...
}

SomeOtherBean has a prototype scope:

@Component
@Scope("prototype")
public SomeOtherBean {
    @Value("...")
    private String configurable;
}

The configurable value needs to be different for each autowired SomeOtherBean and will be supplied via a property placeholder:

configurable.1=foo
configurable.2=bar

Ideally I would like to use annotations to specify the value of the configurable property.

Doing this via XML would be easy but I would like to know whether this is

  • a) impossible with annotations or
  • b) how it can be done.
Ben Turner
  • 131
  • 6

1 Answers1

1

Perhaps this is slightly different to what you are thinking but you could do it easily with an @Configuration-based approach, for example:

@Configuration
public class Config {

    @Bean
    @Scope("prototype")
    public SomeOtherBean someOtherBean1(@Value("${configurable.1}") String value) {
        SomeOtherBean bean = new SomeOtherBean();
        bean.setConfigurable(value);
        return bean;
    }

    @Bean
    @Scope("prototype")
    public SomeOtherBean someOtherBean2(@Value("${configurable.2}") String value) {
        // etc...
    }
}
Jonathan
  • 20,053
  • 6
  • 63
  • 70
  • Good idea Jonathan, that solution does work as desired. However it does clutter up my code with very Spring-specific code that has no business use at all - the very opposite of what Spring annotations should be :-) – Ben Turner Sep 25 '13 at 12:30
  • And why does that clutter your code? This is basically only configuration, which you otherwise would put in xml. – M. Deinum Sep 25 '13 at 14:16
  • As I said, the solution proposed by Jonathan works as desired, but it doesn't answer my question. I would still like to know whether there is some mechanism that allows `@Scope("prototype")` defined `@Component`s to be configured automagically with different `@Value`s. It might not be possible. – Ben Turner Sep 26 '13 at 08:25