Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a property of the current bean in Spring EL

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;
}
like image 319
ironchefpython Avatar asked May 10 '16 19:05

ironchefpython


1 Answers

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>
like image 93
Ernest Sadykov Avatar answered Oct 30 '22 05:10

Ernest Sadykov