5

I know that I can create objects from properties file line properties. I'd like to get a dynamic array of objects, something like this.

application.properties

heroes.hero1=1,superman,kent
heroes.hero2=2,batman,wayne

Let's say that sometime somebody will add another hero to the file. Is it possible for spring to automatically understand additions to array of heroes? Is there a solution to this? Or is it just easier to read and construct such objects from txt files.

Deniss M.
  • 3,617
  • 17
  • 52
  • 100
  • 1
    Possible duplicate of [Spring .properties file: get element as an Array](https://stackoverflow.com/questions/6212898/spring-properties-file-get-element-as-an-array) – cнŝdk Dec 11 '17 at 12:57
  • @chsdk it is not the same question. They are getting array from property value I want an array of properties. – Deniss M. Dec 11 '17 at 12:59

3 Answers3

6

You can actually implement this using Spring Boot Core Functionality:

Create for instance a new Java Class (with use of Lombok for Getters/ Setters now)

@ConfigurationProperties(prefix = "heroes")
@Getter
@Setter
public class HeroesProperties {

    private Map<String, List<String>> heroesMapping;

}

And in your application.properties you can add dynamically more heroes in your way.

E.g.

  • heroes.hero1=1,superman,kent
  • heroes.hero2=2,xx,aa
  • heroes.hero3=3,yy,bb
  • heroes.heroN=4,zz,cc
mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52
1

inject Environment and call getProperty :

import org.springframework.core.env.Environment;   

@Autowired
private Environment env;

public String[] getHero() {
   return env.getProperty("heroes",String[].class);
}
Amir Azizkhani
  • 1,662
  • 17
  • 30
0

Yes, you can. Use following code for injecting these properties:

@Value("${heroes.hero1}")
private String[] heroes1;

@Value("${heroes.hero2}")
private String[] heroes2;
user987339
  • 10,519
  • 8
  • 40
  • 45
  • 3
    I understand this. But what about the second part asked: `Let's say that sometime somebody will add another hero to the file. Is it possible for spring to automatically understand additions to array of heroes?` – Deniss M. Dec 11 '17 at 12:56
  • No it is not possible. This are properties and they are loaded at boot time. Yo will have to handle this case yourself. – user987339 Dec 11 '17 at 12:59
  • It want be recognised without app restart. – user987339 Dec 11 '17 at 13:00
  • true, but it's ok. as long as a semi pro user can change the properties and restart the app - i'm fine with it. he doesn't need to go into the code much. – Deniss M. Dec 11 '17 at 13:02
  • Yes, I agree on that. – user987339 Dec 11 '17 at 13:02