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

其他-如何使用外部配置中指定的标准类名创建Bean?

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

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

我正在使用Spring Boot,并有一个名为的外部配置文件application.yml

在此文件中,假设我有一个foo将完全限定的类名作为值的属性

使用Java配置,创建foo属性指定类型的bean的典型方法是什么

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

我想这foo是在实现一些已知的接口。否则,创建未知类型的bean是毫无意义的。

就像是:

@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;
  }

}