How to insert a key value properties file using Spring?

I have a key value properties file containing error codes and their error messages.

I would like to add this file when I start the application so that I can search on the attached property without having to read the file.

Below is the pseudocode, is there anything in Spring

that could create this setting?

@Value(location = "classpath:app.properties")
private Properties props;

      

whereas app.properties contains:

error1=test
error2=bla
...

      

If not, how can I achieve this without spring?

0


source to share


4 answers


Thanks to the help of "kocko", the following setup works as expected only with the annotation configuration:

@Bean(name = "errors")
public PropertiesFactoryBean mapper() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("errors.properties"));
    return bean;
}

@Resource(name = "errors")
private Properties errors;

      



Or if the resource is not supposed to be exposed as a bean, but simply loaded internally @Component

:

@Component
public class MyLoader {
    private Properties keys;

    @PostConstruct
    public void init() throws IOException {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource("app.properties"));
        bean.afterPropertiesSet();
        keys = bean.getObject();
    }
}

      

+1


source


You can first declare the properties files as such using <util:properties>

in your Spring config:

<util:properties id="messages" location="classpath:app.properties" />

      

This registers a bean with a name messages

that you can autowire / inject into other beans.



@Autowired
@Qualifier("messages")
private Properties props;

      

Additional Information:

+1


source


I do it like this in my project

  <bean id="myPropertyHolder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
         <value>classpath:myApplication.properties</value> 
      </list>
    </property>
  </bean>

      

Then use the property as shown below

<property name="testProperty" value="${testProperty}" />

      

0


source


@M Sach You can also use location locations instead of locations so you don't need to use a list

0


source







All Articles