Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify an instance-specific @Value in a @Scope("prototype") bean using annotations?

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.
like image 980
Ben Turner Avatar asked Nov 11 '22 21:11

Ben Turner


1 Answers

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...
    }
}
like image 64
Jonathan Avatar answered Nov 14 '22 22:11

Jonathan