-1

I am able to read (value of 'fruits') from property file in my spring boot application, successfully using @Value as below.

@Value("${fruits}")
private String[] fruitarray;

from the below

file:applicaton.properties

#section_1
fruits=apple,mango,banana
#section_2
apple.native=aaaa
apple.cost=100
apple.name=xxyyzz

Now, I would like to know, how can I access the key-values from the section_2 of the properties file dynamically. I mean,... in our above code we already got array of fruits and set it to 'fruitarray' using @Value. Now how would I be accessing value for 'apple.native' by using fruitarray[0] variable in java/spring-boot way?

Thanks

Community
  • 1
  • 1
dzoneuser
  • 63
  • 1
  • 7

3 Answers3

1

It's as easy as that:

    @Value("${apple.native}")
    private String Native;

    @Value("${apple.cost}")
    private Double cost;

    @Value("${apple.name}")
    private String name;
dbl
  • 1,109
  • 9
  • 17
0

You could try to get all the properties as a Bean and access dynamically to your properties while looping over the fruits list :

@Autowired
private Environment env;
...
env.getProperty(fruits[i] + ".native");
...

Source : http://www.baeldung.com/properties-with-spring#usage

Anthony BONNIER
  • 355
  • 2
  • 8
  • spring boot by default provides the application.properties injected so no need to do this all. – Alien Aug 03 '18 at 12:22
0

You can define the properties file in the following way also

key.0=value0
key.1=value1

/** Return array from properties file. Array must be defined as "key.0=value0", "key.1=value1", ... */ public List getSystemStringProperties(String key) {

// result list
List<String> result = new LinkedList<>();

// defining variable for assignment in loop condition part
String value;

// next value loading defined in condition part
for(int i = 0; (value = YOUR_PROPERTY_OBJECT.getProperty(key + "." + i)) != null; i++) {
    result.add(value);
}

// return
return result;

}