1

I'm working on a Spring Boot project where I want an array of strings to be defined in my application.yml file. I want to use Spring to inject this array into a variable for use inside of one of my classes as below:

@Component
Class foo {
    @Value("${properties.ymlArray}")
    private ArrayList<String> fooArray;

    @Value("${properties.ymlArray[1]}")
    private String itemFromFooArray;
}

My YML file is as follows:

properties:
  ymlArray: [item1, item2, item3]

In the above example itemFromFooArray populates correctly, getting an item from the array, but I have not found the appropriate way to inject the entire array into a variable.

Any ideas? Thanks!

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
nsprenkle
  • 191
  • 11
  • 1
    This topic help you:
    [https://stackoverflow.com/questions/26699385/spring-boot-yaml-configuration-for-a-list-of-strings](https://stackoverflow.com/questions/26699385/spring-boot-yaml-configuration-for-a-list-of-strings)
    – peterzinho16 Jan 26 '18 at 19:49

1 Answers1

0

Create a configuration class like this:

@Configuration
@ConfigurationProperties("properties")
@Getter
@Setter
public class MyConfig {
  List<String> ymlArray;
}

@ConfigurationProperties(<propName>) specifies what property value in your application.yml to read. You can Autowire this in your foo class to get access to those property values.

@Component
Class foo {
    @Autowired
     MyConfig myConfig;
}

myConfig.getYmlArray() will have the array with all three values.

nsprenkle
  • 191
  • 11
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • 1
    What package do the Getter and Setter annotations come from? I was able to make it work by creating my own getter/setters but would like to be able to use the annotations. – nsprenkle Feb 14 '18 at 19:36
  • 2
    @nsprenkle they most likely come from `Lombok` library to reduce boilerplate code – komidawi Feb 03 '21 at 13:18