Using properties in Spring - bahkified/Notes GitHub Wiki
There are several options when using .properties files in Spring. When using either of these methods, you must make sure that you pull the beans from the Spring context. If you directly instantiate the class, instead of getting it from Spring, the annotations will have no effect, so the injected properties will never be injected. They will always be null!
You can use this annotation on an individual field in a class to automatically populate the field with the value from the properties file. For this to work properly, Spring must know about the properties file in the appropriate context.
For example, in an app-servlet.xml:
<!-- <context:annotation-config></context:annotation-config> -->
<context:component-scan base-package="com.example.package" /> <!-- preferred -->
<util:properties id="urls" location="classpath:app.properties"/>
Note the first line enables values to be inserted into fields that are autodiscovered by Spring. Instead of the annotation-config, you can use context:component-scan
. The component-scan will do everything that annotation-config does plus more.
Now that the properties file is included in the Spring context, you can use the values held within it. To do this, simply declare a String field in your class and use the @Value("#{propFile.property}")
annotation.
@Component
public class MyClass {
@Value("#{propFile.propertyName}")
private String propVal;
}
The PropertiesFactoryBean class can be used to get property files from the Spring context. This is a properties bean that is automatically populated with the properties from the given properties file. It can be autowired into a class field of type java.util.Properties using the id reference.
Example:
appContext.xml
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:application.properties"/>
</bean>
SomeClass.java
@Component
public class SomeClass {
@Resource(name = "applicationProperties")
private Properties props;
public void someMethod() {
// Use the properties class as normal!
String myVal = props.getProperty("my.value");
...
}
}