Read Properties File Key Value Spring Java Class

Read Properties File Key Value Spring Java Class

These are the things people forget all the time at-least in my case for sure hopefully you are also in the same boat. So keep this thing handy somewhere so that we can refer anytime. This one is if you want to read properties file key in your java class while using Spring framework in your application:

  • Sample.properties:
allowed.product=option,stock
test=javahonk
name=test
city=ny
  • Properties files placeholder in your context:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:hibernate/hibernate.${environment.target}.properties</value> <!-- If your properties file inside hibernate folder and you are reading env variable to append with file name -->
			<value>classpath:messaging/messaging.properties</value> <!--If you properties file inside messaging directory -->
			<value>Sample.properties</value> <!-- Your file is in root level -->
		</list>
	</property>
	<property name="ignoreUnresolvablePlaceholders" value="true"/>
	<property name="ignoreResourceNotFound" value="true"/>
</bean>
  • Read in class:
class JavaHonk {
  @Value("${allowed.product}")
  private String allowedProdcuts;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}
  • You could also do this:
<context:property-placeholder location="classpath*:Sample.properties"/>
  • OR if above doesn’t work:
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:Sample.properties</value>
    </list>
  </property>
</bean>
@Component
class JavaHonk {
  @Resource(name="myProperties")
  private Properties myProperties;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *