如何根据 属性 文件中定义的 属性 自动装配子类的实例

How to Autowired an instance of a subclass based on a property that is defined in property file

我使用 SpringBoot 2.2.2.RELEASE(很旧)并且我有以下要求:

我有一个@Service class,我想通过添加一个接口来扩展它的构造函数。当应用程序加载时,我希望接口的正确实例是基于某些 属性 的 @Autowired,我将在 属性 文件中定义。所以这基本上是一个工厂,它通过 属性 文件中定义的一些 属性 实例化 classes。

这是我想象中的工作方式的片段:

@Service
class MyService {

   @Autowired
   public MyService(Shape shape) { ...}
}


interface Shape { ...}

class Circle implements Shape { ... }

class Rectangle implements Shape { ... }

魔法应该存在于某个工厂 class 中,它从 属性 文件中读取 属性 并相应地实例化 [=13= 的子 class 之一].

此应用程序的每个实例都在专用计算机 (EC2) 上运行,具有自己独特的 属性 个文件。

Spring 引导中是否内置了类似的东西?

如有任何建议,我们将不胜感激!

实现它的一种方法是在属性具有特定值时使用 @ConditionalOnProperty 注释来实例化 bean。您可以使用 matchIfMissing = true 来确定默认行为。

@Bean
@ConditionalOnProperty(name = "shape", havingValue = "circle", matchIfMissing = true)
public Shape circleShape() {
    return new Circle();
}

@Bean
@ConditionalOnProperty(name = "shape", havingValue = "rectangle")
public Shape rectangleShape() {
    return new Rectangle();
}