Error creating bean with name 'clienteController': Unsatisfied dependency expressed through field 'clienteService';

huangapple go评论66阅读模式
英文:

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;
}

我尝试过但没有解决的事情:

  1. 使用 @ComponentScan("com.simulacao.api") 注释主类。
  2. 将服务类标记为 @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 &#39;clienteController&#39;: Unsatisfied dependency expressed through field &#39;clienteService&#39;; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;clienteService&#39; 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 &#39;clienteRepository&#39; 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&lt;Cliente, String&gt; {
Cliente buscarClientePorId(String id);
Cliente buscarClientePorNome(String nome);
Optional&lt;Cliente&gt; 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&lt;Cliente&gt; 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&lt;Cliente&gt; 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(&quot;api/clientes&quot;)
@Api(value = &quot;API Rest Clientes&quot;)
@CrossOrigin(origins = &quot;*&quot;)
public class ClienteController {
@Autowired
private ClienteService clienteService;
@Autowired
private ContaService contaService;
@Autowired
private ClienteRepository clienteRepository;
@GetMapping
@ApiOperation(value = &quot;Retorna uma lista de clientes&quot;)
public ResponseEntity&lt;List&lt;Cliente&gt;&gt; listarTodos() {
return ResponseEntity.ok(this.clienteService.listarTodos());
}
@GetMapping(&quot;/{cpf}&quot;)
@ApiOperation(value = &quot;Retorna os dados de um cliente&quot;)
public ResponseEntity&lt;Cliente&gt; dadosCliente(@PathVariable String cpf) {
Optional&lt;Cliente&gt; cliente = clienteRepository.buscarClientePorCpf(cpf);
return cliente.map(ResponseEntity::ok)
.orElseGet(() -&gt; ResponseEntity.notFound().build());
}
@PostMapping
@ApiOperation(value = &quot;Salva um cliente&quot;)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity&lt;Cliente&gt; cadastrar(@Valid @RequestBody Cliente cliente) {
if (!clienteRepository.existsById(cliente.getCpf())) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(this.clienteService.salvar(cliente));
}
@PutMapping(&quot;depositar/{id}&quot;)
@ApiOperation(value = &quot;Realiza um deposito na conta&quot;)
public ResponseEntity&lt;?&gt; depositar(@PathVariable double valor, @PathVariable String id){
this.contaService.depositar(valor);
return new ResponseEntity&lt;&gt;(HttpStatus.OK);
}
@PutMapping(path = &quot;sacar/{id}&quot;)
@ApiOperation(value = &quot;Realiza um saque na conta&quot;)
public ResponseEntity&lt;?&gt; sacar(@PathVariable double valor, @PathVariable String id) throws Exception {
if (valor &lt;= 0) {
throw new Exception(&quot;valor incorreto&quot;);
}
this.contaService.sacar(valor);
return new ResponseEntity&lt;&gt;(HttpStatus.OK);
}
// Hist&#243;rico de transa&#231;&#245;es
@GetMapping(path = &quot;extratoConta/{id}&quot;)
@ApiOperation(value = &quot;Retorna uma lista de movimenta&#231;&#245;es&quot;)
public ResponseEntity&lt;?&gt; extratoConta(@PathVariable String id){
List&lt;Transacao&gt; transacoes = contaService.extratoConta(id);
return new ResponseEntity&lt;&gt;(transacoes,HttpStatus.OK);
}
@DeleteMapping(&quot;/{clienteId}&quot;)
@ApiOperation(value = &quot;Remove um cliente&quot;)
public ResponseEntity&lt;Void&gt; 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 = &quot;Nome n&#227;o pode ser vazio&quot;)
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&lt;Cliente, 
String&gt; {
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&lt;Cliente, 
String&gt; {
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 &quot;Property name&quot;

huangapple
  • 本文由 发表于 2020年9月23日 02:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64015521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定