Home > Software engineering >  Parameter 0 of constructor in 'com.example..'. required a bean of type 'com.example..
Parameter 0 of constructor in 'com.example..'. required a bean of type 'com.example..

Time:06-30

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:

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", 
                "[email protected]", 
                LocalDate.of(2000, Month.JANUARY, 5), 
                22)
        );
    }

}

CodePudding user response:

There is no bean defined for the StudentService class. try defining the class with the following :

  1. @Service - If the StudentService class need to defined as a service class
  2. @Component

either of the way will work for you.

CodePudding user response:

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>
  • Related