Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parameter 0 of constructor in 'com.example..'. required a bean of type 'com.example…' that could not be found

I’m building my first Spring project, I have very little experience in Java and I’m overwhelmed by the amount of boiler plate. This issue seems to be really simple and I found a lot of related answers. However, none of them seems to address this issue specifically.
I haven’t done any special configurations, I only built this with Spring Boot and created 3 classes.
When I run the project I get the following message:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.demo.Student.StudentController required a bean of type 'com.example.demo.Student.StudentService' that could not be found.


Action:

Consider defining a bean of type 'com.example.demo.Student.StudentService' in your configuration.

I renamed the class "StudentService", and maybe this is the source of the issue.

This is my project structure:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

project structure

And this is StudentService.java:

package com.example.demo.Student;

import java.time.LocalDate;
import java.time.Month;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;

public class StudentService {
    
    @GetMapping
    public List<Student> getStudents() {
        return List.of(
            new Student(
                1L, 
                "George", 
                "george.email@gmail.com", 
                LocalDate.of(2000, Month.JANUARY, 5), 
                22)
        );
    }

}

>Solution :

Several ways to resolve this !

  1. Annotate your StudentService class with @Component, during start up of application, Spring will identify this and create a bean in IOC container for use. ( Don’t forget to use @ComponentScan(basePackages={com.example.demo.Stude...}) on top of your DemoApplication class )

  2. Create a Configuration class with @Configuration and define your own bean with @Bean returning instance of StudentService

Eventually, use @Autowired on top of your StudentService instance in Controller. Like below

<pre>public class Controller
{
@Autowired
StudentService service; 
// so on 
} </pre>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading