我在Spring 4.0(使用Spring Boot)环境中遇到以下情况:
映射界面:
public interface EntityModelMapper<ENTITY extends AbstractEntity, MODEL extends AbstractModel>{ }
映射实现:
@Component
public class ProductEntityModelMapper implements EntityModelMapper<Product, ProductModel>{ }
服务:
public interface CrudService<MODEL extends AbstractModel>{ }
我想做一个像这样的抽象父类(super class)服务:
public abstract AbstractCrudService<ENTITY extends AbstractEntity, MODEL extends AbstractModel> implements CrudService<MODEL>{
@Autowired
private EntityModelMapper<ENTITY, MODEL> mapper;
public EntityModelMapper<ENTITY, MODEL> getMapper(){
return mapper;
}
}
所以我可以有这样的实现:
@Service
public ProductCrudService extends AbstractCrudService<Product, ProductModel>{
public void someMethod(Product product){
ProductModel model = getMapper().map(product);
}
}
但是 Spring 告诉我它找不到 EntityModelMapper 的合格 bean 来注入(inject)服务类。这种情况是否可能,我做错了什么,或者我是否突破了 Spring 依赖注入(inject)的极限?
堆栈跟踪:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productCrudService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.flycatcher.seagull.mapper.EntityModelMapper com.flycatcher.seagull.facade.service.crud.AbstractCrudService.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.flycatcher.seagull.mapper.EntityModelMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
最佳答案
据此: https://spring.io/blog/2013/12/03/spring-framework-4-0-and-java-generics 从 Spring 4.0 版本开始就可以了。
这对我来说也不起作用。 (同样的异常,我使用 4.2.3)。 因此尝试升级到最新版本 - 4.2.6。
如果还是不行的话 您可以使用 @Qualifier 注释并 Autowiring EntityModelMapper 作为子类中的接口(interface),并将 getMapper 定义为抽象:
@Component
@Qualifier("productEntityModelQualifier")
public class ProductEntityModelMapper implements EntityModelMapper<Product, ProductModel>{ }
然后在 ProductCrudService 中:
@Service
public ProductCrudService extends AbstractCrudService<Product, ProductModel>{
@Autowired
@Qualifier("productEntityModelQualifier")
EntityModelMapper<Product, ProductModel> mapper;
@Override
protected EntityModelMapper<Product, ProductModel> getMapper(){return mapper;}
public void someMethod(Product product){
ProductModel model = getMapper().map(product);
}
}
关于java - 在通用父类(super class)中 Autowiring 通用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37112109/