我想知道如何在我的应用程序中使用抽象工厂实现类作为@Service。 我有几个我想要的逻辑提供者,并通过构造函数注入(inject)它们。问题是我不确定我的工厂是否应该有构造函数,如果应该,它是否应该是私有(private)的。
我已将此类注释为@Service,但想知道这是否有任何好处以及最佳实践是什么。 谢谢,抱歉,如果鞋面一团糟,这实际上是我的第一个问题和帖子。
这是我的代码片段:
private final FirstClient first;
private final SecondClient second;
private SentimentFactoryImpl(FirstClient first, SecondCliend second) {
this.first = first;
this.second = second;
}
@Override
public SentimentClient get(String clientName) {
if ("First".equalsIgnoreCase(clientName)) {
return this.first;
} else if ("Second".equalsIgnoreCase(clientName)) {
return this.second;
}
throw new UnknownClientException("Service doesn't provide support for client: " + clientName);
}
最佳答案
事实上Spring框架的核心是一种 super 灵活和强大的抽象工厂。如果您使用的是 Spring,则应将所有类创建功能委托(delegate)给 Spring 核心。在您的情况下,我更喜欢使用 Spring java Configurations
来创建类。相当于您在 Spring 中的工厂看起来像那样。
@Configuration
public class ServiceConfig {
@Bean
public SentimentClient firstClient() {
return new FirstClient();
}
@Bean
public SentimentClient secondClient() {
return new SecondClient();
}
}
在这个类被 Spring 核心识别后,它将使用它作为一个工厂来在每次任何其他 Spring bean 需要它时获取服务的实例。您不需要像在工厂中那样调用任何类型的 get
方法。 Spring 会自动执行此操作。
@Service
public class SomeService {
private final SentimentClient firstClient;
@Autowired
private SomeService(SentimentClient firstClient) {
this.firstClient = firstClient;
}
// Some business logic here
}
值得一提的是,Spring配置中工厂方法的名称就是该方法创建的bean(服务)的名称,这个名称加上类类型,用于寻找 Autowiring 所需的bean。
关于java - Spring Boot中的抽象工厂模式@Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58165522/