12

I'd like to create a number of beans from a single class, all to be instantiated in the current application context, each based on prefixed properties in a properties file. I've given an example of what I'm trying to achieve. Any tips on how to do this without excessive code (e.g. without multiple classes, complicated factories, etc.) would be appreciated.

XML configuration:

<bean id="bean1" class="Mybean">
    <property name="prefix" value="bean1"/>
</bean>

<bean id="bean2" class="Mybean">
    <property name="prefix" value="bean2"/>
</bean>

<bean id="bean3" class="Mybean">
    <property name="prefix" value="bean3"/>
</bean>

Properties File:

bean1.name=alfred
bean2.name=bobby
bean3.name=charlie

Class:

class Mybean {
    @Value("${#{prefix}.name}")
    String name;
}

Main Class:

public class Main {
    @Autowired
    List<MyBean> mybeans;
}
ironchefpython
  • 3,409
  • 1
  • 19
  • 32

1 Answers1

2

You can use PropertyPlaceholderConfigurer to set bean's name directly (instead of storing its prefix):

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="app.properties"/>
</bean>

<bean id="bean1" class="Mybean">
    <property name="name" value="${bean1.name}"/>
</bean>

<bean id="bean2" class="Mybean">
    <property name="name" value="${bean2.name}"/>
</bean>

<bean id="bean3" class="Mybean">
    <property name="name" value="${bean3.name}"/>
</bean>
Ernest Sadykov
  • 831
  • 8
  • 28
  • Can you give me an example of how you'd reference the resulting property in Spring EL in a @Value annotation? – ironchefpython May 17 '16 at 18:06
  • I think you find it [here](https://stackoverflow.com/questions/2041558/how-does-spring-3-expression-language-interact-with-property-placeholders?rq=1) – Steffen Harbich May 20 '16 at 12:39
  • That explains how to reference data in the Spring property placeholder bean. It does not explain how to reference properties defined on the *bean* being configured. – ironchefpython May 20 '16 at 14:51
  • Evaluation of `@Value` takes place in bean post processor. Probably, you cannot refer property of the bean that is in process of initialization. – Ernest Sadykov May 20 '16 at 16:09
  • So there's basically no way of providing information in a property set on the bean definition to the bean post processor? That doesn't seem logical. By the way, the reason I need this to be available in a @Value annotation is I'm setting dozens of fields on the bean, and I *really* don't want to add dozens of property values on every bean, I'd rather let provide a prefix and let Spring calculate these fields for me. – ironchefpython May 20 '16 at 19:57