Search code examples
javaspringpropertiesspring-annotations

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 myprops.properties 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


Solution

  • 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;
    }