1

I need to fetch static key value pair data from application.properties file.Is it possible to do so with SpringBoot annotation @Value.

Suggestions would be appreciated.

Example: languageMap={'1'='English','2'='French'}

@Value($("languageMap"))
Map<String,String> languageMap;
RathanaKumar
  • 325
  • 4
  • 14
  • I guess this gets more intuitive if you chose the `application.yml`-format instead of `application.properties`. That format has 'dictionaries' and maps. – Hans Westerbeek Oct 24 '18 at 08:56

4 Answers4

3

You can inject Map using @ConfigurationProperties Annotation as mentioned in the docs.

https://docs.spring.io/spring-boot/docs/1.2.3.RELEASE/reference/htmlsingle/#boot-features-external-config-loading-yaml]

According that docs you can load properties:

language.map[0]='English'

language.map[1]='French'

@ConfigurationProperties(prefix="language")
public class LanguageMap{

    private List<String> languages= new ArrayList<String>();

    public List<String> getLanguages() {
        return this.languages;
    }
}
Raheela Aslam
  • 452
  • 2
  • 13
2

application.properties:

languageMap[1]= English
languageMap[2]= French

Code, just use @ConfigurationProperties and setter method(setLanguageMap) is mandatory for the Map field, otherwise you don't get values.

import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController("/myclass")
@ConfigurationProperties
public class TestControllerEx {

  Map<String, String> languageMap;

  @GetMapping
  public ResponseEntity control() {

    System.out.println(getLanguageMap());

    return new ResponseEntity("success", HttpStatus.OK);
  }

  public Map<String, String> getLanguageMap() {
    return languageMap;
  }

  public void setLanguageMap(Map<String, String> languageMap) {
    this.languageMap = languageMap;
  }
}

output:

{1=English, 2=French}
Molay
  • 1,154
  • 2
  • 19
  • 42
1

Yes, it is possible using @ConfigurableProperties. You have to create a class to access those properties. Take a look at this. In that example, see how additionalHeaders are being accessed. That will help you.

Thiru
  • 2,541
  • 4
  • 25
  • 39
1

Use @ConfigurableProperties and restructure your properties file:

@Configuration
@PropertySource("<prop-file-path>")
@ConfigurationProperties()
public class ConfigProperties {
    @Value($("languageMap"))
    Map<String,String> languageMap;
}

Properties File:

languageMap.1=English
languageMap.2=French
S.K.
  • 3,597
  • 2
  • 16
  • 31