简体   繁体   中英

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 (eg 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;
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM