简体   繁体   中英

how to read properties file using spring and exposed to class

I am using spring 3.0.5 and trying to read properties files to make some kind of validation as well as datasource. But i am getting null when i use @Value ,below are my cfg.

in applicationContext.xml

  <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="classpath:database.properties"/>

  <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <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>// here It is perfectly establishing the data-source.

The Class where I want to exposed the values of properties file

@Component
public class PropertyReaderBean {

//@Value("#{propertyConfigurer1[dailyLimit]}") 
    //@Value("#{database['jdbc.driverClassName']}")
@Value("${jdbc.driverClassName}")// I tried all three but still getting null
private String limit;
public String getLimit() 
{
    System.out.println(" limit : "+limit);
    return limit;
}

public void setLimit(String limit) {
    System.out.println(" limit : "+this.limit);
    this.limit = limit;
}

and finally the databse.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/imps
jdbc.username=root
jdbc.password=root

So whenever i am trying to access the values properties file using above configuration, i am getting null, please guide.

Update: However the setter method of PropertyReaderBean is not working, i have checked the stacktrace, but when i add in xml like this then i can read the properties file values.

<bean id="propertyDao" class="com.alw.imps.validator.PropertyReaderBean">
          <property name="limit" value="${jdbc.password}"></property>
        </bean>  

You don't need property configurer, the definition of which in your code has syntax errors.

You can just do this and reference in code as you have :

  <context:property-placeholder location="classpath:database.properties"/>

which relies on this

 xmlns:context="http://www.springframework.org/schema/context"

and

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd

A likely cause is @Value doesn't work. Did you already declare < context:annotation-config /> in the application context?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM