2

I'm getting reacquainted with Spring and looking at dependency injection and IoC in a way I haven't before.

If I want to build a string, say for a file name, and I already have a Spring bean which contains the directory, what is the best way to append the file name?

Writing a bean to do this myself seems fairly trivial, but I would think that Spring might already have the capability to do this somewhere though its API. If this is possible, how?

Just for kicks, here is the implementation of the fairly simple bean....

public class MySimpleStringAppender {

    private final StringBuffer myString = new StringBuffer();

    public MySimpleStringAppender(List<String> myStrings) {
        for (String string : myStrings) {
            myString.append(string);
        }
    }

    public String getMySimpleString() {
        return myString.toString();
    }

}

and configured with...

<bean id="filename" class="MySimpleStringAppender">
    <constructor-arg ref="filenameStrings"/>
</bean>

<util:list id="filenameStrings">
    <ref bean="directory"/>
    <value>filename.txt</value>
</util:list>

<bean id="directory" class="java.lang.String">
    <constructor-arg value="C:/myDirectory/"/>
</bean>

So while it's not a lot of work or code, I'd think there would be something available so I wouldn't need to write this at all.

2 Answers 2

1

Nope never seen such a thing. You can also make your XML simpler by combining all that into one:

<bean id="filename" class="MySimpleStringAppender">
   <constructor-arg>
      <list>
         <value>C:/myDirectory</value>
         <value>filename.txt</value>
      </list>
   </constructor-arg> 
</bean>

But you probably already knew that.

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe define "c:/myDirectory" as a property and do:

<bean id="filename" class="java.lang.String">
    <constructor-arg value="${dir}/filename.txt"/>
</bean>

Will it work?

1 Comment

(dont forget to include <context:property-placeholder/> or add <bean class="...PropertyPlaceholderConfigurer"/> to your config)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.