views:

298

answers:

2

lets say, I have a lot of stuff within my spring application context which looks like that

<bean name="foo.0001" class="com.example.MyClass">
    <property name="name" value="foo.name.0001"/>
    <property name="zap">
        <bean class="com.example.Other">
            <property name="name" value="foo.name.0001"/>
        </bean>
    </property>
    <property name="bar">
        <bean class="com.example.NextOther">
            <property name="name" value="foo.name.0001"/>
        </bean>
    </property>
</bean>

so the string foo.name.0001 appears within the bean definition several times. Because it is a larger system with several blocks of this configuration, it is quite annoying to modify each of those ids. Ideally I would want to set it only once within a block. Is there a possibility to set some kind of property which exists only in a local scope of a bean definition?

+3  A: 

I'm not sure how that would logically work, as you would still have to reference that value somehow to pass it to the nested beans. If you are worried about defining it multiple times, you can have a look at Springs PropertyPlaceholderConfigurer. It will allow you to the following:

<property name="bar">
   <bean class="com.example.NextOther">
      <property name="name" value="${foo.name.001}"/>
   </bean>
</property>

This would allow you to define it once, and reference it from multiple locations.

Rich Kroll
But if I copy that block I would still have to change **all** occurences of foo.name.001, which is exactly what I'm trying to avoid
Mauli
+1  A: 

It depends how much effort you want to put into to this but your requirements could be fufilled by a spring custom namespace. These are ideal when you have lots of identical blocks of beans each configured differently.

Basically you'd define the xml schema then write a bean definition parser that sets up the beans as required.

See here for more details:

http://www.javaworld.com/javaworld/jw-02-2008/jw-02-springcomponents.html

This is how Spring security simplified its xml configuration.

Pablojim
thanks for the idea, but that would be overkill.
Mauli
Fair enough - but you dont have many other options in spring. You could make a factory class that creates the hierarchy for you.All in all I don't think you'll find a solution to this that doesn't require some effort.
Pablojim