0

Spring Boot JPA Repository

Problem Statement : Want to access JPA repository functions like findAll(); etc inside a normal Java class.

For example : I have created a 1. student.java (model/getter setters) 2. student controller which talks to service 3. student service which talks to repository 4. student repository This all works fine i can get list of all students. localhost/student/all

However now i have a worker class (normal java class working on a thread) and from that worker class i want get student list how can i do that ???

Error I am getting is : java.lang.NullPointerException

I created a object of studentservice inside worker class and tried to access service function to get all students however getting above error.

Same is the case when i create object for student repository.

Please HElpppppp

Student Repository

import org.springframework.data.repository.CrudRepository;
    public interface StudentRepository extends CrudRepository<Student, Integer> {


    }

Student Service class which has StudentRepository as above

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    public List<FxRates> getAllStudents(){
        return (List<FxRates>) studentRepository.findAll();

    }

}

Worker Class :

    @Component
    public class SomeWorker {

        @Autowired
        private StudentService studentService;

        public SomeWorker() {

        }


        public void somefunction() {
System.out.println(studentService); /*** NULL **/
             System.out.println(studentService.getAllStudents());  
/***  Here i get error --> java.lang.NullPointerException ***/
        }


}

Even if i use or @Service and @Configurable in worker class i get error.

KingGraySkull
  • 41
  • 1
  • 5
  • "I created a object of studentservice" .. How are you creating the object ? using new ...()? show the code snippet – pvpkiran Jul 04 '18 at 09:08
  • You need a spring bean in order to access/ inject/ autowire other beans like your repository/ service . – mrkernelpanic Jul 04 '18 at 11:38
  • @pvpkiran g00glen00b mrkernelpanic please have a look added code snippets. – KingGraySkull Jul 04 '18 at 15:04
  • It seems that the class `SomeWorker` is not handled by spring. You have 2 option: 1) solve this issue and make this class handled by spring (the best one I guess) 2) User an applicationcontextaware instance in order to recover spring beans in normal classes not handled by spring like here https://www.concretepage.com/spring/example_applicationcontextaware_spring – Angelo Immediata Jul 04 '18 at 15:10
  • please can you share option1 code sample..Apologies I am learning spring boot – KingGraySkull Jul 04 '18 at 15:19
  • @g00glen00b I have put my code here please can you have a look. Also I checked your solution however still getting error. – KingGraySkull Jul 04 '18 at 18:39

0 Answers0