Spring - IoC Container - How to use dynamic values ​​in properties? (e.g. concat of 2 lines)

I use the Spring framework and I don’t know how to do it: I want to provide a String for the bean, and the string is the result of concatenating several parts, some fixed and other variables

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

How to achieve this using the simplest method?

Many thanks.

+3
source share
3 answers

Job Spring ( Spring 3.0) . factory bean ( , IOC, factory, bean, ).

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
}

bean -

<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"/>
+6

MethodInvokingFactoryBean. , , .

. Javadoc .

+3

init-method

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

Bean

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

Source: https://habr.com/ru/post/1729429/


All Articles