Solucionado (ver solução)
Solucionado
(ver solução)
16
respostas

[Dúvida] UnsatisfiedDependencyException

package med.voll.api.domain.consulta;

import med.voll.api.domain.ValidacaoException; import med.voll.api.domain.consulta.validacoes.ValidadorAgendamentoDeConsulta; import med.voll.api.domain.medico.Medico; import med.voll.api.domain.medico.MedicoRepository; import med.voll.api.domain.paciente.PacienteRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

import java.util.List;

@Service public class AgendaDeConsultas {

@Autowired
private ConsultaRepository consultaRepository;

@Autowired
private MedicoRepository medicoRepository;

@Autowired
private PacienteRepository pacienteRepository;

@Autowired
private List<ValidadorAgendamentoDeConsulta> validadores;

public DadosDetalhamentoConsulta agendar(DadosAgendamentoConsulta dados) {
    if (!pacienteRepository.existsById(dados.idPaciente())) {
        throw new ValidacaoException("Id do paciente informado não existe!");
    }

    if (dados.idMedico() != null && !medicoRepository.existsById(dados.idMedico())) {
        throw new ValidacaoException("Id do médico informado não existe!");
    }

    validadores.forEach(v -> v.validar(dados));

    var paciente = pacienteRepository.getReferenceById(dados.idPaciente());
    var medico = escolherMedico(dados);

    if (medico == null) {
        throw new ValidacaoException("Não existe médico disponível nesta data");
    }

    var consulta = new Consulta(null, medico, paciente, dados.data());

    consultaRepository.save(consulta);

    return new DadosDetalhamentoConsulta(consulta);
}

private Medico escolherMedico(DadosAgendamentoConsulta dados) {
    if (dados.idMedico() != null) {
        return medicoRepository.getReferenceById(dados.idMedico());
    }

    if (dados.especialidade() == null) {
        throw new ValidacaoException("Especialidade é obrigatória quando médico não for escolhido");
    }

    return medicoRepository.escolherMedicoAleatorioLivreNaData(dados.especialidade(), dados.data());
}

}

16 respostas

Tambem estou com o mesmo problema

Oi!

Manda aqui o log completo do erro

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. 2023-03-06T08:41:21.827-03:00 ERROR 2088 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'consultaRepository': Error creating bean with name 'consultaRepository' defined in med.voll.api.domain.consulta.ConsultaRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract boolean med.voll.api.domain.consulta.ConsultaRepository.exixtsByPacienteIdAndDataBetween(java.lang.Long,java.time.LocalDateTime,java.time.LocalDateTime); Reason: Failed to create query for method public abstract boolean med.voll.api.domain.consulta.ConsultaRepository.exixtsByPacienteIdAndDataBetween(java.lang.Long,java.time.LocalDateTime,java.time.LocalDateTime); No property 'exixtsByPacienteId' found for type 'Consulta' at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:712) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:692) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:481) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1397) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[spring-context-6.0.4.jar:6.0.4] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.4.jar:6.0.4] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.2.jar:3.0.2] at med.voll.api.ApiApplication.main(ApiApplication.java:12) ~[classes/:na] at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.0.2.jar:3.0.2]

Reason: Failed to create query for method public abstract boolean med.voll.api.domain.consulta.ConsultaRepository.exixtsByPacienteIdAndDataBetween

No ConsultaRepository o método está com o nome incorreto: exixtsByPacienteIdAndDataBetween

package med.voll.api.domain.consulta.validacoes;

import med.voll.api.domain.ValidacaoException; import med.voll.api.domain.consulta.ConsultaRepository; import med.voll.api.domain.consulta.DadosAgendamentoConsulta; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;

@Component public class ValidadorPacienteSemOutraConsultaNoDia implements ValidadorAgendamentoDeConsulta {

@Autowired
private ConsultaRepository repository;

public void validar(DadosAgendamentoConsulta dados) {
    var primeiroHorario = dados.data().withHour(7);
    var ultimoHorario = dados.data().withHour(18);
    var pacientePossuiOutraConsultaNoDia = repository.existsByPacienteIdAndDataBetween(dados.idPaciente(), primeiroHorario, ultimoHorario);
    if (pacientePossuiOutraConsultaNoDia) {
        throw new ValidacaoException("Paciente já possui uma consulta agendada nesse dia");
    }
}

}

public interface ConsultaRepository extends JpaRepository<Consulta, Long> {
    boolean existsByPacienteIdAndDataBetween(Long idPaciente, LocalDateTime primeiroHorario, LocalDateTime ultimoHorario);

    boolean existsByMedicoIdAndData(Long idMedico, LocalDateTime data);
}

Os nomes estão iguais, e mesmo assim o erro persiste.

posta aqui o log que agora deve ter mudado o erro.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract boolean med.voll.api.domain.medico.MedicoRepository.findAtivoById(java.lang.Long); Reason: Validation failed for query for method public abstract boolean med.voll.api.domain.medico.MedicoRepository.findAtivoById(java.lang.Long) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:712) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:692) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:481) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1397) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[spring-beans-6.0.4.jar:6.0.4] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[spring-context-6.0.4.jar:6.0.4] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.4.jar:6.0.4] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.2.jar:3.0.2] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.2.jar:3.0.2] at med.voll.api.ApiApplication.main(ApiApplication.java:12) ~[classes/:na] at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.0.2.jar:3.0.2]

public interface PacienteRepository extends JpaRepository<Paciente, Long> { Page findAllByAtivoTrue(Pageable paginacao);

@Query("""
        select p.ativo
        from Paciente p
        where 
            p.id = :idPaciente 
        """)
boolean findAtivoById(Long idPaciente);

}

public class ValidadorPacienteAtivo implements ValidadorAgendamentoDeConsulta {

@Autowired
private PacienteRepository repository;

public void validar(DadosAgendamentoConsulta dados) {
    var pacienteEstaAtivo = repository.findAtivoById(dados.idPaciente());
    if (!pacienteEstaAtivo) {
        throw new ValidacaoException("Consulta não pode ser agendada com paciente exluído");
    }
}

}

O problema agora é no MedicoRepository. Posta o código aqui

package med.voll.api.domain.medico;

import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query;

import java.time.LocalDateTime;

public interface MedicoRepository extends JpaRepository<Medico, Long> { Page findAllByAtivoTrue(Pageable paginacao);

@Query("""
        select m from Medico m
        where
            m.ativo = 1 and
            m.especialidade = :especialidade and
            m.id not in(
                select c.medico.id from Consulta c
                where
                c.data = :data
            )
        order by rand()
        limit 1
        """)
Medico escolherMedidoAleatorioLivreNaData(Especialidade especialidade, LocalDateTime data);

@Query("""
        select m.ativo
        from Medico m
        where
            m.id = :idMedico
        """)
Boolean findAtivoById(Long idMedico);

}

private Medico escolherMedico(DadosAgendamentoConsulta dados) {
    if (dados.idMedico() != null) {
        return medicoRepository.getReferenceById(dados.idMedico());
    }

    if (dados.especialidade() == null) {
        throw new ValidacaoException("Especialidade é obrigatória quando médico não for escolhido");
    }

    return medicoRepository.escolherMedidoAleatorioLivreNaData(dados.especialidade(), dados.data());
}

está ocorrendo erro neste método

solução!

Esse campo na classe consulta estava com a letra minúscula, só foi alterar isso que deu certo, @Entity(name = "Consulta")