我怎样才能在 Spring Boot 中有两个相同 class 的实现(测试和实际)?

How can I have two implementations(test and actual) of same class in SpringBoot?

我想要两个 类 实现相同的接口,但一个应该在测试 运行 时使用,一个应该在实际代码 运行 时执行。这个要看环境。因此,如果环境是“CI”,则应使用测试实现,如果环境是“开发”或“生产”,则应使用实际实现。如何使用 SpringBoot 并遵循最佳实践来实现这一点?

一种方法是根据条件将 class 作为组件加载。

1.You 可以利用 Spring 配置文件.

@Profile("Cl") 

这将根据激活的 spring 配置文件相应地加载所需的 class。

在application.properties

spring.profiles.active=CL

示例代码:

public interface Sample {
    void runData();
}


@Component
@Profile("CL")
public class TestSample implements Sample {
    
    @Override
    public void runData(){
        // your code
    }
}

同样,您可以为 Dev

中需要的其他 class 设置配置文件

2.You也可以利用@ConditionalOnProperty(name="propertyname" , havingValue="true")

您可以通过在 application.properties 文件中为相应的环境设置“propertyname”来控制它

application.properties

propertyname=true

示例代码:

@Component
@ConditionalOnProperty(name="propertyname" , havingValue="true")
public class TestSample implements Sample {
    
    @Override
    public void runData(){
        // your code
    }
}