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
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.
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.
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.
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.
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
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With