Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - IoC Container - How to use dynamic values in properties ? (like a concat of 2 Strings)

Tags:

java

spring

I'm using Spring framework and I don't know how to do this simple thing: I want to provide a String to a bean, with the string being the result of the concatenation of multiple part, some fixed and other variables

For example it could be something like: "myReportFile_20102101_1832.txt" - the first part is a fixed part - the second part is a timestamp with current date time - the last part is another fixed part

How to achieve that using the simplest way ?

Thanks a lot.

like image 688
Guillaume Avatar asked Jan 18 '26 06:01

Guillaume


1 Answers

That sounds like a Job for the Spring Expression Language (introduced in Spring 3.0) to me. Though it might be easier to use a factory bean for that task (it gets the static information injected via IOC and offers a factory method that instantiates your other bean including the calculated dynamic information). Like so

class FileNameFactoryBean
{
    private Date date = new Date();
    private String prefix;
    private String postfix;

    public OtherBean createBean()
    {
        String filename = prefix + date.toString() + postfix;
        return new OtherBean(filename);
    }

    // Getters and Setters
}

And then in your bean configuration something like

<bean id="fileNameFactory" class="package.FileNameFactoryBean">
    <property name="prefix" value="file_" />
    <property name="postfix" value=".txt" />
</bean>

<bean id="otherBean" factory-bean="fileNameFactory" factory-method="createBean"/>
like image 136
Daff Avatar answered Jan 20 '26 19:01

Daff