Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring .properties file: get element as an Array

I'm loading properties attributes from a .properties file using Spring as follows:

file: elements.properties base.module.elementToSearch=1 base.module.elementToSearch=2 base.module.elementToSearch=3 base.module.elementToSearch=4 base.module.elementToSearch=5 base.module.elementToSearch=6 

The spring xml file

file: myapplication.xml <bean id="some"       class="com.some.Class">       <property name="property" value="#{base.module.elementToSearch}" /> </bean> 

And my Class.java

file: Class.java public void setProperty(final List<Integer> elements){     this.elements = elements; } 

But when debugging, the parameter elements only get the last element into the list, so, there is a list of one element with value "6", instead of a list with 6 elements.

I tried other approaches, like adding in value only #{base.module} but then it finds no parameter in the properties file.

A workaround is to have in elements.properties file a list separated by commas, like:

base.module.elementToSearch=1,2,3,4,5,6 

and use it as a String and parse it, but is there a better solution?

like image 698
RamonBoza Avatar asked Jun 02 '11 09:06

RamonBoza


People also ask

How do I read multiple values from application properties in Spring boot?

We use a singleton bean whose properties map to entries in 3 separate properties files. This is the main class to read properties from multiple properties files into an object in Spring Boot. We use @PropertySource and locations of the files in the classpath. The application.

How do I get a list of Spring boot application properties?

To see all properties in your Spring Boot application, enable the Actuator endpoint called env . This enables an HTTP endpoint which shows all the properties of your application's environment. You can do this by setting the property management.

How use value from properties file in Spring boot?

Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.


1 Answers

If you define your array in properties file like:

base.module.elementToSearch=1,2,3,4,5,6 

You can load such array in your Java class like this:

  @Value("${base.module.elementToSearch}")   private String[] elementToSearch; 
like image 76
svlada Avatar answered Sep 27 '22 20:09

svlada