Spring Property Consolidation

I have a Spring bean:

<bean id="sharedBean" class="com.bean.SharedBean">
    <constructor-arg name="app-name" value="#{ config['app.name'] }"/>
</bean>

      

This bean is defined in a jar and is used in two applications that are deployed to the same tomcat server. I only have one properties file that applications are redistributed to, and I would like to save it that way if possible. You can see the problem - I need two values ​​for app.name (one for each web app).

I need to set app.name myself in each application. I don't mind hard-coding a value in Java (but I don't think I can enter a value in that direction). I know I can present a different properties file in a different path and override, but I hope I can accomplish this through Spring, allowing me to only maintain one common properties file.

+3


source to share


1 answer


Possible solutions in the recommended order:

1 - is there a reason why the generic bean is declared in a separate jar file? Of course, the bean class can be located there, but why not declare the actual bean inside the individual web applications where it is used?

2 - if you absolutely need to keep the bean definition in a shared jar, you can use bean inheritance ; (a) change the bean class to use a property, not the arg constructor:

<bean id="sharedBean" class="com.bean.SharedBean">
    <property name="app-name" value="default"/>
</bean>

      

(b) in your web application context file:



<bean id="instanceBean" parent="sharedBean">
    <property name="app-name" value="app1"/>
</bean>

      

3 - use the Spring profile; in your general jar context.xml:

<beans profile="app1">
    <bean id="sharedBean" class="com.bean.SharedBean">
        <constructor-arg name="app-name" value="app1"/>
    </bean>
</beans>

<beans profile="app2">
    <bean id="sharedBean" class="com.bean.SharedBean">
        <constructor-arg name="app-name" value="app2"/>
    </bean>
</beans>

note: <beans profile=... MUST be the last entries in your context file.

      

Add a context parameter to each web.xml (changing the value):

<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>app1</param-value>
</context-param>

      

+1


source







All Articles