【发布时间】:2016-10-07 07:56:34
【问题描述】:
使用 Spring Boot 进行 Java 项目。
我有一个通用服务
@Service
public class GenericService
还有几个继承GenericService的类:
@Service
public class Entity1Service extends GenericService
@Service
public class Entity2Service extends GenericService
实体类:
@MappedSuperclass
public class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ENTITY_SEQ")
private Long id;
@Enumerated(EnumType.STRING)
private ProcessState processState;
}
@Entity
public class Entity1 extends AbstractEntity {
// some specific fields
}
@Entity
public class Entity2 extends AbstractEntity {
// some specific fields
}
我必须在两个子类中编写类似的方法,在基类中编写一个泛型方法:
@Service
public class Entity1Service extends GenericService {
public void startEntity1Process(AbstractEntity entity) {
Entity1 entity1 = (Entity1) entity;
// perform some specific operations
}
}
@Service
public class Entity2Service extends GenericService {
public void startEntity2Process(AbstractEntity entity) {
Entity2 entity2 = (Entity2) entity;
// perform some specific operations
}
}
我在基类中写了一个泛型方法:
@Service
public class GenericService {
@Autowired
Entity1Service entity1Service;
@Autowired
Entity1Service entity2Service;
public void startEntityProcess(AbstractEntity entity) {
if (entity instance of Entity1)
entity1Service.startEntity1Process(entity);
else if (entity instance of Entity2)
entity2Service.startEntity2Process(entity);
}
}
我收到了错误:
原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [com.process.Entity1Service] 的合格 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
我建议,错误的原因是我试图在父类中自动装配子类的 bean。
1.在当前的实现中如何避免这个错误?
2。有没有更好的解决方案来解决这类任务?
也许我必须尝试将public void startEntityProcess(AbstractEntity entity) 声明为抽象然后覆盖它?但是我将如何区分实体实例呢?
【问题讨论】:
-
您能否通过组件扫描显示您的配置。您确定正在扫描 Entity1Service 吗?
-
是的,它是单独工作的。此错误仅在父类中自动装配后发生。该服务在其他几个类中自动装配并且工作正常。
标签: java spring spring-mvc inheritance abstract-class