[java] 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?

This question is related to java spring placeholder properties-file

The answer is


And incase you a different delimiter other than comma, you can use that as well.

@Value("#{'${my.config.values}'.split(',')}")
private String[] myValues;   // could also be a List<String>

and

in your application properties you could have

my.config.values=value1, value2, value3

Here is an example of how you can do it in Spring 4.0+

application.properties content:

some.key=yes,no,cancel

Java Code:

@Autowire
private Environment env;

...

String[] springRocks = env.getProperty("some.key", String[].class);

If you need to pass the asterisk symbol, you have to wrap it with quotes.

In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.

In yml file I have:

websocket:
  cors: "*"

In Config class I have:

@Value("${websocket.cors}")
private String[] cors;

With a Spring Boot one can do the following:

application.properties

values[0]=abc
values[1]=def

Configuration class

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties
public class Configuration {

    List<String> values = new ArrayList<>();

    public List<String> getValues() {
        return values;
    }

}

This is needed, without this class or without the values in class it is not working.

Spring Boot Application class

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);

    // notice #{} is used instead of ${}
    @Value("#{configuration.values}")
    List<String> values;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootConsoleApplication.class, args);
    }

    @Override
    public void run(String... args) {
        LOG.info("values: {}", values);
    }

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to placeholder

Keep placeholder text in UITextField on input in IOS HTML Input - already filled in text Add placeholder text inside UITextView in Swift? Bootstrap select dropdown list placeholder fail to change placeholder color with Bootstrap 3 Not showing placeholder for input type="date" field Use Font Awesome Icon in Placeholder How do I put hint in a asp:textbox How to support placeholder attribute in IE8 and 9 HTML5 image icon to input placeholder

Examples related to properties-file

How to access a value defined in the application.properties file in Spring Boot adding comment in .properties files How to read values from properties file? Spring .properties file: get element as an Array Where to place and how to read configuration resource files in servlet based application? How to read an external properties file in Maven Loading a properties file from Java package