tags:

views:

222

answers:

2

Hi -

is it possible to define in a spring context file, and one or more properties that can be accessed in <bean> elements.

The example below illustrates best what I need - I want to define the property FOO once and then reference it multiple times in my various <bean> definitions:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"&gt;
  <properties>
    <property name="FOO" value="BAR">
  </properties>

  <bean name="TEST" class="mytest">
    <property name="MYFOO" value="${FOO}"/>
  </bean>
  <bean name="TEST1" class="mytest1">
    <property name="MYFOO" value="${FOO}"/>
  </bean>

</beans>

Any input would be much appreciated.
Thanks, Kevin.

+3  A: 

You can do this using the snappily-named PropertyPlaceHolderConfigurer. See here for the example in the spring docs. You don't define the property values themselves in the spring beans file, you externalise them in a .properties file.

You could, I suspect, use PropertyPlaceHolderConfigurer or one of its siblings to inject a Properties object defined inside your Spring file, but that would be a rather more verbose solution.

skaffman
+2  A: 

If you only need to define them in your xml file and never change them (like you would change a configuration option, say a port or an ip), you can create a bean of class String with the given property and then write . Creating a bean of class String isn't the most straight forward thing, but it's doable.

If you want something more complicated (say you want a configuration file residing outside the jar where your xml with the bean definition is), you can look at the PropertyPlaceholderConfigurer class.

laura