Мой класс ресурсов не находит служебный компонент, определенный в приложении Spring Boot

#spring-boot

#spring-boot

Вопрос:

Я определил компонент Student Service:

 @Component
public class StudentService {

    private final StudentDao studentDao;

    @Autowired
    public StudentService(@Qualifier("fakeDao") StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    //for the sake of relevance not putting other methods here, but I have all CRUD methods defined here 
    //in the class.
}
  

Мой класс StudentResource выглядит следующим образом:

 @RestController
@RequestMapping("api/v1/students")
public class StudentResource {

    @Autowired
    private final StudentService studentService;

    public StudentResource(StudentService studentService) {
        this.studentService = studentService;
    }
}
  

Когда я запускаю приложение, я получаю следующую ошибку:

 Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    [2m2020-10-05 22:06:19.236[0;39m [31mERROR[0;39m [35m7228[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter  [0;39m [2m:[0;39m 
    
***************************
APPLICATION FAILED TO START
***************************
    
Description:
    
Parameter 0 of constructor in com.centene.demo.resource.StudentResource required a bean of type 'org.centene.demo.service.StudentService' that could not be found.
    
    
Action:
Consider defining a bean of type 'org.centene.demo.service.StudentService' in your configuration.
  

просто некоторая информация об используемых версиях:
JAva 1.8
Весенняя загрузка 2.3.4

Ответ №1:

Проблема с вашим StudentDao классом в том, что вы пытаетесь выполнить автоматическое подключение. Я думаю, вы забыли создать конфигурации компонента для StudentDao . Поместите @Configuration или @Service в начало StudentDao объявления вашего класса и повторите попытку. Он должен работать.

Комментарии:

1. Я попробовал это, и все равно ошибка не исчезает. Позвольте мне поместить код в интерфейс StudentDao.

2. общедоступный интерфейс StudentDao { int insertNewStudent(UUID StudentID, Student student); …..}

3. это интерфейс, где находится реализация интерфейса? Вы помещаете аннотацию в класс реализации

4. @Repository(«fakeDao») общедоступный класс FakeStudentDaoImpl реализует StudentDao { частная конечная карта <UUID, Student> база данных; общедоступный FakeStudentDaoImpl() { база данных = новая хэш-карта<>(); }

5. Хорошо, я удалил аннотацию из интерфейса StudentDao и вставил код в реализацию класса. FakeStudentDaoImpl, который помечен @Repository

Ответ №2:

Я разобрался с проблемой. По-видимому, проблема была в моей структуре пакета. Пакет класса StudentService был написан неправильно, начиная с «org.centene.demo …», а не «com.centene.demo ..». Это важно, поскольку все остальные пакеты начинались с com.centene.demo