[英]Factory for Spring Beans implementing interface
Considering a project of many entities, I have a service that requires to know the entity's type to execute a method.考虑到许多实体的项目,我有一项服务需要知道实体的类型才能执行方法。 I created;
我建立;
interface Service<T> {
String myMethod(T entity)
Class<T> getResponsibility()
And for example;例如;
class FooService<Foo> {
String myMethod(Foo entity) { return 'foo'; }
Class<Foo> getResponsibility() { return Foo.class }
I wanted to create a factory to return the correct Bean (I'm using Spring Boot) to use, which I defined:我想创建一个工厂来返回正确的 Bean(我正在使用 Spring Boot)来使用,我定义了:
class ServiceFactory {
List<Service<?>> services;
@Autowired
public ServiceFactory(List<Service<?>> services) {
this.services = services;
}
Service getFor(Object entity) {
// Simplified for comprehension purpose
return this.services.stream().filter(service -> service.getResponsibility().equals(entity.getClass()).get();
}
This works, but I have a (sonar) warning saying that I should not make 'raw' use of Service
as return type for my factory method.这可行,但我有一个(声纳)警告说我不应该“原始”使用
Service
作为我的工厂方法的返回类型。 What is the correct way of achieving this?实现这一目标的正确方法是什么? Using a wildcard is another warning.
使用通配符是另一个警告。
The goal is to have a factory that returns the correct Bean.目标是拥有一个返回正确 Bean 的工厂。 Is the initial design wrong?
最初的设计错了吗?
Instead of passing an object, pass the class itself and capture it as a method type parameter:不要传递 object,而是传递 class 本身并将其作为方法类型参数捕获:
<T> Service<T> getFor(Class<T> type) {
You'd still get a warning because the injected list uses a wildcard:您仍然会收到警告,因为注入的列表使用通配符:
@SuppressWarnings("unchecked")
<T> Service<T> getFor(Class<T> type) {
// Simplified for comprehension purpose
return (Service<T>) this.services.stream()
.filter(service -> service.getResponsibility().equals(type))
.findFirst()
.get();
}
You might be better off using Spring's support for generics by injecting directly the specific service:通过直接注入特定服务,您可能会更好地使用Spring 对 generics 的支持:
@Autowired
Service<Foo> fooService;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.