When a properties file is used in a Spring ApplicationContext, its properties may be accessed in this manner: ${someproperty} inside your xml configuration files. But how do you access the same property within your java code without injecting it via xml?
ApplicationContext config
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="myapp.properties" />
</bean>
<bean class="my.app.MyClass">
<property name="foo" value="${someproperty}" />
</bean>
</beans>
Properties
someproperty=somevalue
Update 1
The actual point of this, is a special case where a unique id for the application is set in the properties file (ez editing by sysadmin). Several of the application classes implement ApplicationContextAware so they have access to the context and to prevent injecting in each class or defining a bean for every class we want an ez property access method. Our app “knowing” about Spring is not an issue in this case.
It doesn’t have any sense to access a property, it contradicts the IoC principle, the main aim of the Spring. In additional to other answers, may be you need all properties? In this case there is a
PropertiesFactoryBeanobject which could give youPropertiesobject to have access for all properties.The
PropertyPlaceholderConfigurerbean is designed to replace placeholders in a spring context. Any other usages are just confusing at least.