tags:

views:

89

answers:

3

I have three apps in a Spring 2.5 managed project that share some code and differ in details.

Each application has a property (java.lang.String) which is used before the application context is built.

Building the app context takes some time and cannot happen first. As such, it's defined in each individual application. This property is duplicated in the context definition since it is also needed there. Can I get rid of that duplication?

Is it possible to inject that property into my application context?

+4  A: 

Have a look at PropertyPlaceholderConfigurer.

The Spring documentation talks about it here.

<bean id="myPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:my-property-file.properties"/>
    <property name="placeholderPrefix" value="$myPrefix{"/>
</bean>

<bean id="myClassWhichUsesTheProperties" class="com.class.Name">
    <property name="propertyName" value="$myPrefix{my.property.from.the.file}"/>
</bean>

You then have reference to that String to anywhere you'd like in your application context, constructor-arg, property etc.

Noel M
Yet I cannot use my, say `private String appName = ...` , in the application context as a property for some beans, can I?
DerMike
No, as that is Java syntax, and the application context is an XML file. If you have a property file and that contains the property for appName, eg, `appName=MyApp`, then you can refer to `$myPrefix{appName}` once the PropertyPlaceholderConfigurer is set up, and that (in this case) would resolve to `MyApp`.
Noel M
I hoped to find something like `ctx.addBean(String.class, appName)` at best.
DerMike
+3  A: 

With spring 3.0 you have the @Value("${property}"). It uses the defined PropertyPlaceholderConfigurer beans.

In spring 2.5 you can again use the PropertyPlaceholderConfigurer and then define a bean of type java.lang.String which you can then autowire:

<bean id="yourProperty" class="java.lang.String">
    <constructor-arg value="${property}" />
</bean>

@Autowired
@Qualifier("yourProperty")
private String property;
Bozho
A: 

If you don't want to deal with external properties,you could define some common bean

<bean id="parent" class="my.class.Name"/>

then initialize it somehow, and put into common spring xml file, lets say common.xml. After that, you can make this context as a parent for each or your apps - in your child context xml file:

<import resource="common.xml"/>

and then you can inject properties of your parent into the beans you're interested in:

<bean ...
<property name="myProperty" value="#{parent.commonProperty}"/>
...
</bean>
denis_k