tags:

views:

405

answers:

3

Hello,

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.

+3  A: 

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"/>
Daff
Thanks a lot. I found the expression language more simple and natural, but as I'm with spring 2.5, I'll go with the Factory Bean.
Guillaume
+3  A: 

Use the MethodInvokingFactoryBean. You can give it a static method on another class that takes a file name and appends a timestamp to it, or whatever other logic you might like to have.

See the Javadoc for more info, and an example.

danben
A: 

You can delegate that logic to an init-method

<bean id="myBean" class="foo.MyBean" init-method="nameBuilder">
    <property name="pre" value="myReportFile_" />
    <property name="ext" value=".txt" />
</bean>

and then in your Bean Class

public class MyBean {
....
    public void nameBuilder() {
       setName(pre+System.currentTimeMillis()+ext); //or anything you want..
    }
}
Mauricio