简体   繁体   中英

Getting error while using @Autowired in the springboot

I am creating a Springboot project in which I have two service interfaces whom I am injecting in my Controller

StudentService

public interface StudentService {

    void addStudent(Student student);
    //other functions
}

TeacherService

public interface TeacherService {

    void addStudent(Teacher teacher);
    //other functions
}

When I am using @Autowired for the StudentService it is working fine but I am getting an error when I am using @Autowired for the TeacherService in my Controller.I try alot but did not find the cause of the error.

My Controllers

@Controller
public class StudentController {

    @Autowired
    StudenService studenService;
    ....
    ....
}
@Controller
public class TeacherController {

    @Autowired
    TeacherService teacherService;
    ....
    ....
}

annotate the service class with @Service annotation

@Service public interface TeacherService {

void addStudent(Teacher teacher);
//other functions

}

Try using @Service on the ServiceImpl class and try again. I think that should fix your issue.

The @Autowired will be used to create a link between two objectS inside the container. it seems that you used @service or @component in the StudentService implementation and missed it in the TeacherService implementation.

Please make sure to use @component for the TeacherService implementation. so in this way the object will be created inside the container.

@Service or @component
public class TeacherServiceImp implements TeacherService {
//your code
}

We can also use @Component here to create bean for TeacherServiceImpl class. I think both will work same.

@Service
public class TeacherServiceImp implements TeacherService {
//your codes 
}
@Component
public class TeacherServiceImp implements TeacherService {
//your codes 
}

This type of error generally happens when you might have not used @Service at your Service implementation or The service interface has not been implemented yet.

@Service
public class TeacherServiceImp implements TeacherService {
//your codes
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM