英文:
Error creating bean with name 'clienteController': Unsatisfied dependency expressed through field 'clienteService';
问题
以下是翻译好的内容:
我试图启动我的Spring Boot应用程序,但是下面的错误信息返回给我:
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为 'clienteController' 的bean时出错:通过字段 'clienteService' 表达的不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为 'clienteService' 的bean时出错:在文件 [C:\Users\RenanFreitasDevenz\Documents\api-simulacao\target\classes\com\simulacao\api\services\ClienteService.class] 中定义的bean 'clienteService':通过构造函数参数 0 表达的不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.BeanCreationException: 创建名为 'clienteRepository' 的bean时出错:在 MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration 上声明的 @EnableMongoRepositories 中定义的 com.simulacao.api.repository.ClienteRepository:调用初始化方法失败;嵌套异常是 org.springframework.data.mapping.PropertyReferenceException: 对于类型 Cliente,找不到属性 buscarClientePorId!
ClienteRepository 类:
package com.simulacao.api.repository;
import com.simulacao.api.documents.Cliente;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface ClienteRepository extends MongoRepository<Cliente, String> {
Cliente buscarClientePorId(String id);
Cliente buscarClientePorNome(String nome);
Optional<Cliente> buscarClientePorCpf(String cpf);
}
ClienteService 类:
package com.simulacao.api.services;
import com.simulacao.api.repository.ClienteRepository;
import com.simulacao.api.documents.Cliente;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
public class ClienteService {
@Autowired
private final ClienteRepository clienteRepository;
public ClienteService(ClienteRepository clienteRepository) {
this.clienteRepository = clienteRepository;
}
public List<Cliente> listarTodos() {
return this.clienteRepository.findAll();
}
public Cliente listarPorId(String id) {
return clienteRepository.buscarClientePorId(id);
}
public Cliente listarPorNome(String nome) {
return clienteRepository.buscarClientePorNome(nome);
}
public Cliente salvar(Cliente cliente) {
return this.clienteRepository.save(cliente);
}
public Cliente atualizar(Cliente cliente) {
return this.clienteRepository.save(cliente);
}
public Optional<Cliente> verificarCliente(String cpf) {
return this.clienteRepository.buscarClientePorCpf(cpf);
}
public void remover(String id) {
clienteRepository.deleteById(id);
}
}
ClienteController 类:
package com.simulacao.api.controller;
import com.simulacao.api.documents.Cliente;
import com.simulacao.api.documents.Transacao;
import com.simulacao.api.repository.ClienteRepository;
import com.simulacao.api.services.ClienteService;
import com.simulacao.api.services.ContaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("api/clientes")
@Api(value = "API Rest Clientes")
@CrossOrigin(origins = "*")
public class ClienteController {
@Autowired
private ClienteService clienteService;
@Autowired
private ContaService contaService;
@Autowired
private ClienteRepository clienteRepository;
@GetMapping
@ApiOperation(value = "Retorna uma lista de clientes")
public ResponseEntity<List<Cliente>> listarTodos() {
return ResponseEntity.ok(this.clienteService.listarTodos());
}
@GetMapping("/{cpf}")
@ApiOperation(value = "Retorna os dados de um cliente")
public ResponseEntity<Cliente> dadosCliente(@PathVariable String cpf) {
Optional<Cliente> cliente = clienteRepository.buscarClientePorCpf(cpf);
return cliente.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping
@ApiOperation(value = "Salva um cliente")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Cliente> cadastrar(@Valid @RequestBody Cliente cliente) {
if (!clienteRepository.existsById(cliente.getCpf())) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(this.clienteService.salvar(cliente));
}
// 其他代码部分已省略...
}
Cliente 类:
package com.simulacao.api.documents;
import lombok.*;
import org.hibernate.validator.constraints.br.CPF;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotEmpty;
@Document
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Cliente {
@Id
private String id;
@NotEmpty(message = "Nome não pode ser vazio")
private String nome;
@Indexed(unique = true)
@CPF
private String cpf;
private Conta conta;
private boolean ativo;
}
我尝试过但没有解决的事情:
- 使用 @ComponentScan("com.simulacao.api") 注释主类。
- 将服务类标记为 @Service。
如果需要更多的代码片段,请告诉我。
有什么可以做的吗?
英文:
I'm trying to start my Spring Boot application but the error below is returning me:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clienteController': Unsatisfied dependency expressed through field 'clienteService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clienteService' defined in file [C:\Users\RenanFreitasDevenz\Documents\api-simulacao\target\classes\com\simulacao\api\services\ClienteService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clienteRepository' defined in com.simulacao.api.repository.ClienteRepository defined in @EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property buscarClientePorId found for type Cliente!
Class ClienteRepository:
package com.simulacao.api.repository;
import com.simulacao.api.documents.Cliente;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface ClienteRepository extends MongoRepository<Cliente, String> {
Cliente buscarClientePorId(String id);
Cliente buscarClientePorNome(String nome);
Optional<Cliente> buscarClientePorCpf(String cpf);
}
Class ClienteService:
package com.simulacao.api.services;
import com.simulacao.api.repository.ClienteRepository;
import com.simulacao.api.documents.Cliente;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
public class ClienteService {
@Autowired
private final ClienteRepository clienteRepository;
public ClienteService(ClienteRepository clienteRepository) {
this.clienteRepository = clienteRepository;
}
public List<Cliente> listarTodos() {
return this.clienteRepository.findAll();
}
public Cliente listarPorId(String id) {
return clienteRepository.buscarClientePorId(id);
}
public Cliente listarPorNome(String nome) {
return clienteRepository.buscarClientePorNome(nome);
}
public Cliente salvar(Cliente cliente) {
return this.clienteRepository.save(cliente);
}
public Cliente atualizar(Cliente cliente) {
return this.clienteRepository.save(cliente);
}
public Optional<Cliente> verificarCliente(String cpf) {
return this.clienteRepository.buscarClientePorCpf(cpf);
}
public void remover(String id) {
clienteRepository.deleteById(id);
}
}
Class ClienteController:
package com.simulacao.api.controller;
import com.simulacao.api.documents.Cliente;
import com.simulacao.api.documents.Transacao;
import com.simulacao.api.repository.ClienteRepository;
import com.simulacao.api.services.ClienteService;
import com.simulacao.api.services.ContaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("api/clientes")
@Api(value = "API Rest Clientes")
@CrossOrigin(origins = "*")
public class ClienteController {
@Autowired
private ClienteService clienteService;
@Autowired
private ContaService contaService;
@Autowired
private ClienteRepository clienteRepository;
@GetMapping
@ApiOperation(value = "Retorna uma lista de clientes")
public ResponseEntity<List<Cliente>> listarTodos() {
return ResponseEntity.ok(this.clienteService.listarTodos());
}
@GetMapping("/{cpf}")
@ApiOperation(value = "Retorna os dados de um cliente")
public ResponseEntity<Cliente> dadosCliente(@PathVariable String cpf) {
Optional<Cliente> cliente = clienteRepository.buscarClientePorCpf(cpf);
return cliente.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping
@ApiOperation(value = "Salva um cliente")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Cliente> cadastrar(@Valid @RequestBody Cliente cliente) {
if (!clienteRepository.existsById(cliente.getCpf())) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(this.clienteService.salvar(cliente));
}
@PutMapping("depositar/{id}")
@ApiOperation(value = "Realiza um deposito na conta")
public ResponseEntity<?> depositar(@PathVariable double valor, @PathVariable String id){
this.contaService.depositar(valor);
return new ResponseEntity<>(HttpStatus.OK);
}
@PutMapping(path = "sacar/{id}")
@ApiOperation(value = "Realiza um saque na conta")
public ResponseEntity<?> sacar(@PathVariable double valor, @PathVariable String id) throws Exception {
if (valor <= 0) {
throw new Exception("valor incorreto");
}
this.contaService.sacar(valor);
return new ResponseEntity<>(HttpStatus.OK);
}
// Histórico de transações
@GetMapping(path = "extratoConta/{id}")
@ApiOperation(value = "Retorna uma lista de movimentações")
public ResponseEntity<?> extratoConta(@PathVariable String id){
List<Transacao> transacoes = contaService.extratoConta(id);
return new ResponseEntity<>(transacoes,HttpStatus.OK);
}
@DeleteMapping("/{clienteId}")
@ApiOperation(value = "Remove um cliente")
public ResponseEntity<Void> deletar(@PathVariable String clienteId) {
clienteService.remover(clienteId);
return ResponseEntity.noContent().build();
}
}
Class Cliente:
package com.simulacao.api.documents;
import lombok.*;
import org.hibernate.validator.constraints.br.CPF;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotEmpty;
@Document
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Cliente {
@Id
private String id;
@NotEmpty(message = "Nome não pode ser vazio")
private String nome;
@Indexed(unique=true)
@CPF
private String cpf;
private Conta conta;
private boolean ativo;
}
What I tried to do but didn't fix:
1 - Annotate the main class with @ComponentScan ("com.simulacao.api")
2 - Note the class of service with @Service.
If you need me to post any more code snippets, let me know.
What can be done?
答案1
得分: 1
根据你的代码仓库中所看到的情况,你有一个方法 Cliente buscarClientePorId(String id);
和类似的方法。
你正在使用查询方法(Query Methods),它必须类似于 findByFollowedByPropertyOfYourEntity
。
根据 Spring Data Repository 文档,
> Spring Data JPA 进行属性检查并遍历嵌套属性。
根据这个文档修改你的方法,应该就可以工作了。
例如,将你的仓库内方法修改为:
@Repository
public interface ClienteRepository extends MongoRepository<Cliente,
String> {
Cliente findById(String id);
}
英文:
As I can see from your code that in your repository, you have method Cliente buscarClientePorId(String id);
and similar methods.
You are using Query Methods and it must have something like findByFollowedByPropertyOfYourEntity
.
According to the Spring Data Repository docs,
> Spring Data JPA does a property check and traverses nested properties
Change your method according to this docs and it should work.
For instance, change your method inside the repository to
@Repository
public interface ClienteRepository extends MongoRepository<Cliente,
String> {
Cliente findById(String id);
}
答案2
得分: 0
我解决了我的问题。
我必须将存储库的查询适应为:
findByParametro ...
例如:
findBy "属性名称"
英文:
I solved my problem.
I had to adapt the queries of the repository to:
findByParametro ...
Ex:
findBy "Property name"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论