【发布时间】:2020-04-14 05:03:14
【问题描述】:
我在 spring 中创建了一个带有 CrudRepository 实现的 MVC API 并接收 UnsatisfiedDependencyException。
我第一次尝试使用@Autowired注解,但不起作用
控制器代码:
package marcel.pirlog.licenta.userManagement.controllers;
import marcel.pirlog.licenta.userManagement.services.IAccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController("/account")
public class LoginController {
IAccountService accountService;
public LoginController(IAccountService accountService) {
this.accountService = accountService;
}
@RequestMapping(name = "/", method = RequestMethod.GET)
public ResponseEntity<String> getAll(){
return ResponseEntity.ok(accountService.findAll().toString());
}
}
服务代码:
package marcel.pirlog.licenta.userManagement.services;
import marcel.pirlog.licenta.userManagement.entities.AccountEntity;
import marcel.pirlog.licenta.userManagement.repositorys.IAccountRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountService implements IAccountService {
private final IAccountRepository accountRepository;
public AccountService(IAccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Override
public List<AccountEntity> findAll() {
List<AccountEntity> result = (List<AccountEntity>)accountRepository.findAll();
return result;
}
}
存储库代码:
@Repository
public interface IAccountRepository extends CrudRepository<AccountEntity, Long> {
}
收到UnsatisfiedDependencyException:
org.springframework.beans.factory.UnsatisfiedDependencyException: 使用文件中定义的名称“/帐户”创建 bean 时出错 [C:\Users\parlo\Documents\GitHub\licenta\ProiectLicenta\Server\user-management\target\classes\marcel\pirlog\licenta\userManagement\controllers\LoginController.class]: 通过构造函数参数 0 表示的不满足的依赖关系; 嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException: 创建文件中定义的名称为“accountService”的 bean 时出错 [C:\Users\parlo\Documents\GitHub\licenta\ProiectLicenta\Server\user-management\target\classes\marcel\pirlog\licenta\userManagement\services\AccountService.class]: 通过构造函数参数 0 表示的不满足的依赖关系; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建名为“IAccountRepository”的bean:调用init 方法失败;嵌套异常是 java.lang.IllegalArgumentException: 不是托管类型:类 marcel.pirlog.licenta.userManagement.entities.AccountEntity ...
【问题讨论】:
-
您使用的是什么版本的 Spring?在4.3之前(我认为)您仍然需要在@Service的构造函数上添加@Autowire。
-
我将@Autowired 放在服务构造器上,但不起作用。我收到同样的异常
-
@MarcelPirlog 你能清理并安装项目吗?
-
啊 - 在您的 AccountEntity 上添加 @Entity。
-
您的源文件夹似乎有问题。看看这里。 baeldung.com/spring-component-scanning希望这有帮助
标签: java spring spring-boot spring-mvc exception