Search code examples
javaspring-bootjavabeans

How to manually bind ConfigurationProperties to a bean / create bean from ConfigurationProperties in Spring Boot


I use Spring Boot for a project, where configuration files are bound to a bean via

@ConfigurationProperties(prefix="foo.bar", ignoreUnknownFields = true)
class myBean{
  private String propertyA;
  private String propertyB;
  ...
} 

This works quite well, the properties are filled in a process that does not matter much for this problem - it just provides the properties of the prefix defined in the annotation.

However, I would like to create another bean of the same class and have it filled with properties from another file.

Ideally, this would be something like

MyBean otherBean = (MyBean) WhatEverClass.createBeanFromProperties(MyBean.class, Properties myPropertiesFromSomeOtherFile);

Is there some Class which is able to this Properties-to-Bean Mapping?

I have searched for Classes which could implement this functionality. DefaultListableBeanFactory only provides already created Beans but I have no method to point Spring to a specific property file for this bean (except for changing the annotation, but I need the prefix mapped to this bean)


Solution

  • You can refer to the following methods. Can I manually load @ConfigurationProperties without the Spring AppContext?

    Properties myPropertiesFromSomeOtherFile = ...;
    
    ConfigurationPropertySource propertySource = new MapConfigurationPropertySource(myPropertiesFromSomeOtherFile);
    Binder binder = new Binder(propertySource);
    
    MyBean myBean = binder.bind("foo.bar", MyBean.class).get();