how to read properties file in spring project?
You can create an XML based application context like:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
if the xml file is located on your class path. Alternatively, you can use a file on the file system:
ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");
More information is available in the Spring reference docs. You should also register a shutdown hook to ensure graceful shutdown:
ctx.registerShutdownHook();
Next, you can use the PropertyPlaceHolderConfigurer to extract the properties from a '.properties' file and inject them into your beans:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:com/foo/jdbc.properties"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
Lastly, if you prefer annotation based config, you can use the @Value
annotation to inject properties into you beans:
@Component
public class SomeBean {
@Value("${jdbc.url}")
private String jdbcUrl;
}
As of Spring 4, you can use the @PropertySource annotation in a Spring @Configuration
class:
@Configuration
@PropertySource("application.properties")
public class ApplicationConfig {
// more config ...
}
If you would like to have your config outside of your classpath, you can use the file:
prefix:
@PropertySource("file:/path/to/application.properties")
Alternatively, you can use an environmental variable to define the file
@PropertySource("file:${APP_PROPERTIES}")
Where APP_PROPERTIES
is an environmental variable that has the value of the location of the property file, e.g. /path/to/application.properties
.
Please read my blog post Spring @PropertySource for more information about @PropertySource
, its usage, how property values can be overridden and how optional property sources can be specified.