PDA

View Full Version : Accessing custom Properties from within a class


RostockStyle
Mar 21st, 2006, 12:18 PM
Hi:

I have a file called constants.properties and I want to access the properties from within my FormController and from within my DisplayTag's ColumnDecorator subclass. I read that I can load the properties file as follows:


<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyP laceholderConfigurer">
<property name="location" value="/WEB-INF/classes/constants.properties"/>
</bean>


But how do I access the properties from within my Java classes? System.getProperty(...) only gets me the system properties. What API do I have to use?

Michael.

wpoitras
Mar 21st, 2006, 12:49 PM
Like almost everything else with Spring, its injected. You would have it as a property on your FormController and in your XML would look something like:


<property name="myProperty" value="${my.constant}"/>

RostockStyle
Mar 21st, 2006, 01:02 PM
I see, through injection. That makes sense. So for all the objects that are defined in an xml file e.g. myApplication-servlet.xml, I can specify a property. Cool.

But is there a way to get those properties programatically? Maybe I am approaching it wrong and it needs to be done through injection. I have a ColumnDecorator subclass (from the DisplayTag library) and want to return a static URL, I don't want to hard-code that URL in the class, rather wanted to use something similar to System.getProperty("MyURL").

Another question would be, how would I access properties in a Domain object? Or can I use injection there too?

Michael.

EndlessWinter
Mar 21st, 2006, 01:05 PM
Also, you can define the same properties file as MessageSource bean and inject this messageSource in your classes

wpoitras
Mar 21st, 2006, 02:01 PM
For initalizing stateless service objects, injection is probably a good idea because you separate the configuration from the actual object. It allows maximum flexibility in the use of your object. And it tends to make your objects more unit testable.

But, if for some reason that doesn't work in certain situations, you may have to resort to System.getProperty.

As for domain objects, there are two basic methods for initializing domain objects with injections:
- Object factories. Often domain objects are created from some stateless service which governs the creation and persistance of a domain object. The factory would have the configuration parameters injected into it at startup.
- AOP. Typically this means creating aspects using AspectJ where you do dependency injection when the object's "new" method is called. Take a look at AspectJ portion (http://static.springframework.org/spring/docs/1.2.x/reference/aspectj.html#d0e5176) of the reference manual.