tags:

views:

105

answers:

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.

A: 

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.

Gandalf
+1  A: 

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?

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