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

Shv*_*alb 1 java spring spring-boot

我使用 SpringBoot 2.2.2.RELEASE (相当旧的版本),我有以下要求:

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

这是我想象它如何工作的一个片段:

@Service
class MyService {

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


interface Shape { ...}

class Circle implements Shape { ... }

class Rectangle implements Shape { ... }
Run Code Online (Sandbox Code Playgroud)

魔力应该存在于某个 Factory 类中,该类从属性文件中读取属性并相应地实例化Shape.

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

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

任何建议,将不胜感激!

Ale*_*lex 9

实现它的一种方法是@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();
}
Run Code Online (Sandbox Code Playgroud)