几天来,我正在尝试创建 Spring CRUD 应用程序。我很困惑。我无法解决这个错误。
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“clientController”的bean时出错:通过方法“setClientService”参数0表示的不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“clientService”的 bean 时出错:通过字段“clientRepository”表示不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.kopylov.repository.ClientRepository”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
和这个
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“clientService”的bean时出错:通过字段“clientRepository”表示的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.kopylov.repository.ClientRepository”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
客户端控制器
@Controller
public class ClientController {
private ClientService clientService;
@Autowired
@Qualifier("clientService")
public void setClientService(ClientService clientService){
this.clientService=clientService;
}
@RequestMapping(value = "registration/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute Client client){
this.clientService.addClient(client);
return "home";
}
}
ClientServiceImpl
@Service("clientService")
public class ClientServiceImpl implements ClientService{
private ClientRepository clientRepository;
@Autowired
@Qualifier("clientRepository")
public void setClientRepository(ClientRepository clientRepository){
this.clientRepository=clientRepository;
}
@Transactional
public void addClient(Client client){
clientRepository.saveAndFlush(client);
}
}
客户端存储库
public interface ClientRepository extends JpaRepository<Client, Integer> {
}
我查看了很多类似的问题,但没有一个答案对我有帮助。
原文由 kopylov 发布,翻译遵循 CC BY-SA 4.0 许可协议
ClientRepository 应使用
@Repository
标签进行注释。使用您当前的配置,Spring 不会扫描该类并了解它。在启动和连线的那一刻,将找不到 ClientRepository 类。编辑 如果添加
@Repository
标签没有帮助,那么我认为问题可能出在ClientService
和ClientServiceImpl
上。尝试用
@Service
注释ClientService
(接口)。由于您的服务应该只有一个实现,因此您不需要使用可选参数@Service("clientService")
指定名称。 Spring 将根据接口的名称自动生成它。此外,正如布鲁诺所说,在
@Qualifier
中不需要ClientController
因为您只有一个服务实现。客户端服务.java
ClientServiceImpl.java (选项 1)
ClientServiceImpl.java (选项 2/首选)
客户端控制器.java