Trouble with Spring @ConfiurationProperties extending Mao

370 Views Asked by At

I am trying to load come properties from config using the Spring @Configuration & @ConfigurationProperties combination. I have a POJO that extends HashMap<Integer, String> and has a single variable inside. (See MyConfigPojo below). From the .yaml file, I have the same shape. However, when booting up the app, I get an error when trying to parse the string for the defaultValue into an Integer.

@Configuration
@ConfigurationPropeties(prefix = "my-config")
public class MyConfigPojo extends HashMap<Integer, String> {

  private String defaultValue;

  private String getValueForIdOrDefault(int id); // this.get(id) OR ELSE defaultValue
}

In config I have this:

myConfig:
  1: "my first value"
  23: "my 23rd value"
  defaultValue: "cheese"

Which results in a

APPLICATION FAILED TO START
Description:
Failed to bind properties under 'myPackage' to MyConfigPojo:
Property: myConfig[1]
Value: cheese

I thought that was weird, so I turned on TRACE logs and found this:

99 common frames omittedCaused by: java.lang.NumberFormatException: For input string: "defaultValue" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

Is there a way to intercept reading this file or to tell Spring how to set the values properly?

1

There are 1 best solutions below

3
On

You are trying to read a Map from .yml file, for that, you need @ConfigurationProperties annotation enough, don't need @Configuration annotation(if using spring boot). If you are using spring-framework, you need @Configuration also.

Use this example:

myConfig:
  map:
    1: "my first value"
    23: "my 23rd value"
    defaultValue: "cheese"

MyConfigPojo.java

package com.org;


import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.HashMap;

@Configuration
@ConfigurationProperties(prefix = "my-config")
public class MyConfigPojo {

    private HashMap<String, String> map;

    public HashMap<String, String> getMap() {
        return map;
    }

    public void setMap(HashMap<String, String> map) {
        this.map = map;
    }
}

Now, you can Autowire this MyConfigPojo class anywhere(for instance, in controller class) and read those map keys and values.

@Autowired
MyConfigPojo pojo;

Now, you have considered keys & Values as String datatype for that Map, you will not get NumberFormatException.