Sriks Sriks - 1 year ago 118
Java Question

how to read properties file in spring project?

Before post this Question, I google to get Properties from Spring project(Its NOT web-based project). I am confused as every one are talking about application-context.xml and have configuration like

However, I am working on normal Java Project with Spring(NO Web-app and stuff like that). But I would like to get some common properties from properties file and that needs to be used in JAVA file. How can achieve this by using Spring/Spring Annotations?

Where I should configure file under my project and how to invoke through spring?

My understanding is application-context.xml is used ONLY for web based projects. If not, how should I configure this application-context.xml as I do NOT have web.xml to define the application-context.xml

Answer Source

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:


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/"/>

<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}"/>

Lastly, if you prefer annotation based config, you can use the @Value annotation to inject properties into you beans:

public class SomeBean {

    private String jdbcUrl;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download