Issue
public interface CourseRepo extends CrudRepository<Course, Long> {
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UnitOfWork {
CourseRepo courses;
StudentRepository students;
StudyProgramRepository studyPrograms;
StudySchemeRepo studySchemes;
FeeStructureRepository feeStructures;
}
@RestController
public class TestController {
@Autowired
UnitOfWork uow;
@GetMapping("/addcr")
public String addCourse() {
Course cr = new Course();
cr.setTitle("DingDong course");
uow.getCourses().save(cr);
return "course Added..!!" ;
}
APPLICATION FAILED TO START
***************************
Description:
Field uow in com.srs.TestController required a bean of type 'com.srs.uow.UnitOfWork' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.srs.uow.UnitOfWork' in your configuration.
if i remove autowired and add a bean
@RestController
public class TestController {
@Bean
public UnitOfWork uow() {
return new UnitOfWork();
}
@GetMapping("/addcr")
public String addCourse() {
Course cr = new Course();
cr.setTitle("DingDong course");
uow().getCourses().save(cr);
return "course Added..!!" ;
}
java.lang.NullPointerException: Cannot invoke "com.srs.jpa.CourseRepo.save(Object)" because the return value of "com.srs.uow.UnitOfWork.getCourses()" is null
i tried both autowired and in this case how can i use autowired or bean properly ?
Solution
Your class need to be annotated with @Component to be used with DI provider by @Autowired annotation
For the same reason each repository of your class need to be annotated with @Autowired
Answered By - Luca Riccitelli
Answer Checked By - Terry (JavaFixing Volunteer)