0

This is in reference to this question.

Spring Boot - inject map from application.yml

In that question, they have

info:
   build:
      artifact: ${project.artifactId}
      name: ${project.name}
      description: ${project.description}
      version: ${project.version}

To map this into their java code, they are suggesting to use @ConfigurationProperties annotation. The problem with this annotation is that you have to create a New Class and then add this annotation on top of it.

However can I directly get this onto a single field just like how @Value annotation does?

Say I need it here like this:

// Someannotation or any other lean and clean way to get this
@Someannotation("${info}")
private Map<String, Object> map;

The above code should give me a map where key is build and value is some Object with fields like artifact, name etc(of course if this works, I will create a POJO for this instead of leaving it as normal Object).

Note: @ConfigurationProperties does not work on fields which is why I am looking to see if there is a leaner and cleaner way to do this.

P.S. Also I am fine with using @ConfigurationProperties and creating a new class, but I just wanted to see if I am missing out on a simpler way to do this without having to create a new class altogether.

theprogrammer
  • 1,698
  • 7
  • 28
  • 48
  • Of course I know that, hence the question. I am asking to see if there is another approach `similar to @Value` without having to create a new class and then slap in `@ConfigurationProperties` on it. – theprogrammer Nov 04 '19 at 21:29

1 Answers1

1

the only way I know to do so, is to define the value part in JSON format:

app.collection.map.string.to.integer={one:"1", two:"2", three:"3"}

then inject with

@Value("#{${app.collection.map.string.to.integer}}")
private Map<String, Integer> mapStringToInteger;

from https://relentlesscoding.com/2018/09/09/spring-basics-dynamically-inject-values-with-springs-value/ in section Inject Maps With Spring’s @Value

Devilluminati
  • 328
  • 1
  • 15