0

I am getting

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of com.ykb.frd.fraudcore.configuration.DatabaseConfiguration, problem: null

exception while reading the YAML file. And application tries over and over again until it crashes because of Stack Overflow exception

YAML file:

db:
  url: blablablaurl
  user: blabla
  password: blabla

Java:

@JsonIgnoreProperties(ignoreUnknown = true)
public class DatabaseConfiguration {
    private Database db;
    private static DatabaseConfiguration single_instance = null;

    private DatabaseConfiguration() {
        db = readYml();
    }

    public static DatabaseConfiguration getInstance() {
        if (single_instance == null)
            single_instance = new DatabaseConfiguration();

        return single_instance;
    }

    private final String YML_PATH = //path;

    public Database getDb() {
        return db;
    }

    /**
     * Read from application.yml
     * @return Database object
     */
    private Database readYml(){
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            return mapper.readValue(new File(YML_PATH), DatabaseConfiguration.class).getDb();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Inside of readYml() function, infinite loop occurs on top of mapper.readValue. I guess its about singleton object but I am not sure.

Calling database configuration:

private DatabaseConfiguration database = DatabaseConfiguration.getInstance();

Thanks.

Berkin
  • 1,565
  • 5
  • 22
  • 48
  • 1
    This isn't a stack over flow error, Where did you get that from? – SamHoque Oct 26 '18 at 08:03
  • Yeah you are right, code try to return Database object from readYml over and over again until application crashes because of StackOverflow – Berkin Oct 26 '18 at 08:06

1 Answers1

2

The class cannot be a singleton. Jackson needs a public default constructor. You should use a different class - effectively a DTO - to deserialize the YAML and then pass that object to your singleton.

By the way, singleton is an antipattern.

Michael
  • 41,989
  • 11
  • 82
  • 128