鉴于特定服务 API 的两个(或更多)实现,根据应用程序属性选择在我的应用程序运行时使用哪一个的最佳方法是什么?
示例 API:
public interface Greeting {
String sayHello(String username);
}
实现:
public class FriendlyGreeting implements Greeting {
public String sayHello(String username) {
return "Hello, " + username;
}
}
public class HostileGreeting implements Greeting {
public String sayHello(String username) {
return "Go away, " + username;
}
}
我有一个带有 @Autowired
构造函数的单独服务类,该构造函数采用 Greeting
的实例。我想要的是基于配置属性来决定注入(inject)和使用哪个问候实现。我想出了使用配置类来做出决定:
@Configuration
public class GreetingConfiguration {
private String selection;
@Autowired
public GreetingConfiguration(@Value("${greeting.type}") String type) {
this.selection = type;
}
@Bean
public Greeting provideGreeting() {
if ("friendly".equals(selection)) {
return new FriendlyGreeting();
} else {
return new HostileGreeting();
}
}
}
这是做我想做的正确的方式吗?我在实现上使用 @Qualifier
的道路上,结果一团糟,Spring 看到了我的 Greeting
API 的 3 个实例,无论如何我都需要一个配置来选择要使用的实现并在其上返回一个唯一的限定符名称,这感觉比我决定的要糟糕。
最佳答案
您可以将两个问候语都标记为@Service 并使用@Qualifier("yourServiceHere") 选择所选的一个,如下所示:
@Autowired
@Qualifier("friendlyGreeting")
private Greeting greeting;
另一种方法是使用配置文件。您可以使用 @Service 和 @Profile("friendly") 标记您的 FriendlyGreeting 服务,使用 @Service 和 @Profile("hostileGreeting") 标记 HostileGreeting 服务,然后将以下内容放入 application.properties 中:
spring.profiles.active=friendly
关于java - 决定在 Spring Boot 应用程序中使用多个实现中的哪一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54334908/