Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Custom properties in aplicationContext.xml Spring file

I need to store some configuration parameters for a web application that uses spring framework.

Typically I'll use a configurationfile.properties file but i wonder if i can store that values in the applicationContext.xml file.

One workaround could be to create a JavaBean class to store the values, and build that class using spring, something like this:

<bean id="configurationBean" class="mypackage.someClass">
 <property name="confValue1">
   <value>myValue1</value>
 </property>
 ....
</bean>

But i would like to know if is there a way to store those parameters without the needing to create that class.

Thanks in advance.


I think that the best solution that fits my requirements is to use a java.util.Properties instance as a Spring Bean.

Thank you all.

like image 640
HyLian Avatar asked May 20 '09 15:05

HyLian


People also ask

Where should ApplicationContext XML be placed?

It needs to be in the classpath. You can put the original editable instance anywhere (e.g. a config directory off the root) but then you will need to have your build management tool (e.g. Ant or Maven ) copy it into the classpath for the runtime.

What is required to load the beans configured in ApplicationContext XML file?

ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH.

What is ApplicationContext XML file in Spring?

Applicationcontext. xml - It is standard spring context file which contains all beans and the configuration that are common among all the servlets. It is optional file in case of web app. Spring uses ContextLoaderListener to load this file in case of web application. Spring-servlet.

How read properties file in Spring XML?

This page shows how to load property file from the classpath using xml based configuration. Declare your property file in your xml based configuration file using "context:property-placeholder" tag, and refer property key any where in the xml based configuration file using ${db. host. url} syntax.


1 Answers

This should work with the following syntax.

<bean id="props" class="java.util.Properties" >
    <constructor-arg>
        <props>
            <prop key="myKey">myValue</prop>
            <prop ...>
        </props>
    </constructor-arg>
</bean>

You are taking advantage of the fact that java.util.Properties has a copy constructor that takes a Properties object.

I do this for a HashSet which also has a copy constructor (as do HashMaps and ArrayLists) and it works perfectly.

like image 53
Darren Greaves Avatar answered Sep 30 '22 04:09

Darren Greaves