简体   繁体   中英

How to concatenate two String beans in a configuration file in Spring 2.5

I know that Spring 3.0 and up has EL, but in this case the project is using Spring 2.5 , example:

<bean id="dir" class="java.lang.String">
    <constructor-arg value="c:/work/"
</bean>

<bean id="file" class="java.lang.String">
    <constructor-arg value="file.properties" />
</bean>

<bean id="path" class="java.lang.String">
    <constructor-arg value=**dir +  file**/>
</bean>

Does this work?

<bean id="dir" class="java.lang.String">
    <constructor-arg value="c:/work/"
</bean>

<bean id="file" class="java.lang.String">
    <constructor-arg value="file.properties" />
</bean>

<bean id="path" factory-bean="dir" factory-method="concat">
    <constructor-arg ref="file"/>
</bean>

Notice the usage of String.concat(java.lang.String) method as factory-method .

But XML isn't really the best place for stuff like this, what about Java @Configuration ?

@Configuration
public class Cfg {
    @Bean
    public String dir() {
        return "c:/work/";
    }

    @Bean
    public String file() {
        return "file.properties";
    }

    @Bean
    public String path() {
        return dir() + file();
    }
}

Spring is not the place to store application logic like this.

If you need that, add a getPath() method that does something like:

public String getPath() {
    if(path == null) {
        path = getDir() + getPath();
    }
    return path;
}

Have you tried to use Spring-EL? Take a look at this LINK

With Spring-EL you can do something like the following:

<bean id="dir" class="java.lang.String">
    <property name="path" value="c:/work/" />
</bean>
<bean id="file" class="java.lang.String">
    <property name="fileName" value="file.properties" />
</bean>
<bean id="path" class="java.lang.String">
    <property name="initialShapeSeed" value="#{dir.path}#{file.fileName}"/>
</bean>

This is available since Spring 3.0.

You can use ref instead of value. Ie

<bean id="path" class="java.lang.String">
    <constructor-arg ref="file"/>
</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