4
respostas

UnsatisfiedDependencyException ao subir a aplicação

Olá!

Estou fazendo o curso "Agilidade e TDD: um dia no desenvolvimento de software", na segunda vídeo aula da seção "Implementando uma feature".

Baixei o projeto e apenas adicionei os códigos indicados nas aulas, mas quando tento subir a aplicação, me retornam as exceções:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'aircraftModelController' defined in file [C:\Users\maite.refosco\Desktop\Alura - Java\clines\target\classes\br\com\caelum\clines\api\aircraftmodels\AircraftModelController.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'aircraftModelService' defined in file [C:\Users\maite.refosco\Desktop\Alura - Java\clines\target\classes\br\com\caelum\clines\api\aircraftmodels\AircraftModelService.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'aircraftModelRepository' defined in br.com.caelum.clines.api.aircraftmodels.AircraftModelRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class br.com.caelum.clines.shared.domain.AircraftModel
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'aircraftModelRepository' defined in br.com.caelum.clines.api.aircraftmodels.AircraftModelRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class br.com.caelum.clines.shared.domain.AircraftModel
Caused by: java.lang.IllegalArgumentException: Not a managed type: class br.com.caelum.clines.shared.domain.AircraftModel

Classes que os erros se referem:

AircraftModelController:

package br.com.caelum.clines.api.aircraftmodels;

import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;

import static org.springframework.http.ResponseEntity.created;

@RestController
@RequestMapping("aircraft-model")
@AllArgsConstructor
public class AircraftModelController {
    private final AircraftModelService service;

    @PostMapping
    ResponseEntity<?> createBy(@RequestBody @Valid AircraftModelForm form) {
        var id = service.createAircraftModelBy(form);

        var uri = URI.create("/aircraft-model/").resolve(String.valueOf(id));

        return created(uri).build();
    }

    @GetMapping
    List<AircraftModelView> list() {
        return service.listAllAircraftModels();
    }

    @GetMapping("{id}")
    AircraftModelView show(@PathVariable Long id) {
        return service.showAircraftModelBy(id);
    }
}

AircraftModelService:

package br.com.caelum.clines.api.aircraftmodels;

import br.com.caelum.clines.shared.exceptions.ResourceAlreadyExistsException;
import br.com.caelum.clines.shared.exceptions.ResourceNotFoundException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
@AllArgsConstructor
public class AircraftModelService {

    private final AircraftModelRepository repository;
    private final AircraftModelFormMapper formMapper;
    private final AircraftModelViewMapper viewMapper;

    public Long createAircraftModelBy(AircraftModelForm form) {
        repository.findByDescription(form.getDescription()).ifPresent(
                (existingAircraftModel) -> {
                    throw new ResourceAlreadyExistsException("Aircraft Model already exists");
                });
        var aircraftModel = formMapper.map(form);

        repository.save(aircraftModel);

        return aircraftModel.getId();
    }

    public List<AircraftModelView> listAllAircraftModels() {
        return repository.findAll().stream().map(viewMapper::map).collect(toList());
    }

    public AircraftModelView showAircraftModelBy(Long aircraftModelId) {
        var aircraftModel = repository.findById(aircraftModelId).orElseThrow(() -> new ResourceNotFoundException("Cannot find aircraft model"));
        return viewMapper.map(aircraftModel);
    }
}
4 respostas

Restante do código:

AircraftModelRepository:

package br.com.caelum.clines.api.aircraftmodels;

import br.com.caelum.clines.api.aircraft.ExistingAircraftModelService;
import br.com.caelum.clines.shared.domain.AircraftModel;
import org.springframework.data.repository.Repository;

import java.util.List;
import java.util.Optional;

public interface AircraftModelRepository extends Repository<AircraftModel, Long>, ExistingAircraftModelService {
    void save(AircraftModel aircraftModel);
    List<AircraftModel> findAll();
    Optional<AircraftModel> findByDescription(String description);
    Optional<AircraftModel> findById(Long id);
}

AircraftModel:

package br.com.caelum.clines.shared.domain;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Getter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "aircraft_models")
public class AircraftModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String description;


    public AircraftModel(String description) {
        this.description = description;
    }
}

Agradeço desde já

Oi Maite!

Talvez seja problema com o Lombok. No Eclipse você precisa realizar a instalação dele manualmente.

Olá, Rodrigo!

Então, eu estou usando o Intellij e, no início, o lombok e a JPA não estava compilando, aí precisei fazer a importação de dependência pelo maven indicado pela IDE. Depois que fiz isso, ambas as anotações passaram a compilar (acho que tive até que importar o jakarta também, se não me engano). Uma outra coisa que fiz, que esqueci de comentar, eu alterei a versão java para 17.

Ah entendi.

Talvez seja problemas com a versão do Java, pois o projeto do curso utiliza versões antigas dos frameworks, que são compatíveis com o Java 8.