Warm tip: This article is reproduced from serverfault.com, please click

How to create a bean from a fully-qualified class name specified in external configuration? (Spring)

发布于 2020-11-28 17:41:36

I'm using Spring Boot and have an external configuration file called application.yml.

In this file, suppose I have a property foo that takes a fully-qualified class name as value.

Using Java configuration, what is the typical way to create a bean of the type specified by the foo property?

Questioner
Jack
Viewed
0
Dirk Deyne 2020-11-29 03:03:41

I suppose that foo is implementing some known interface. Otherwise, it is kind of pointless to create a bean of an unknown Type.

Something like:

@Configuration
public class FooConfiguration {

  @Value("foo.class-name") // ref to the key used in you application.yml
  private String fooClassName;

  @Bean
  public FooInterface fooBean(){
    FooInterface fooImpl = Class.forName(fooClassName).newInstance(); // concreet implemetation
    return fooImpl;
  }

}