Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a string array of properties in Spring?

I have the following in my application.properties file

some.server.url[0]=http://url
some.server.url[1]=http://otherUrl

How do I refer to the array of properties using the @Value anotation inside a @Bean method?

I am using Java 6 with Tomcat 7 and Spring boot 1.4

like image 298
SebS Avatar asked Aug 16 '16 23:08

SebS


People also ask

How do you bind an application property in spring boot?

As of Spring Boot 2.2, we can use the @ConstructorBinding annotation to bind our configuration properties. This essentially means that @ConfigurationProperties-annotated classes may now be immutable.

Can we have multiple property files in spring boot?

properties” property file, as it was automatically built inside the Spring boot application when the project is initially created. We can create and maintain multiple property files within “Resources” module, where we will be able to define different types of property values in different files.

How do I get a list of properties in spring boot?

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.

How read multiple values from properties file in Java 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.


2 Answers

I was also having the same problem as you mentioned and it seems using index form on application.properties was not working for me either.

To solve the problem I did something like below

some.server.url = url1, url2

Then to get the those properties I simply use @Value

@Value("${some.server.url}")
private String[] urls ;

Spring automatically splits the String with comma and return you an Array. AFAIK this was introduced in Spring 4+

If you don't want comma (,) as seperator you have to use SpEL like below.

@Value("#{'${some.server.url}'.split(',')}")
private List<String> urls;

where split() accepts the seperator

like image 194
A0__oN Avatar answered Oct 08 '22 18:10

A0__oN


You can use a collection.

@Value("${some.server.url}")
private List<String> urls;

You can also use a configuration class and inject the bean into your other class:

@Component
@ConfigurationProperties("some.server")
public class SomeConfiguration {
    private List<String> url;

    public List<String> getUrl() {
        return url;
    }

    public void setUrl(List<String> url) {
        this.url = url;
    }
}
like image 29
Shawn Clark Avatar answered Oct 08 '22 17:10

Shawn Clark