I am new to Spring and I wish to implement threads. I have tried the conventional Java run() method to send a database writing task to the thread. However, this causes a NullPointerException every time I am calling the database dao or service query within the run() method. If I place the query in the constructor then it works.
I think possibly I am not able to instantiate the dao/service variable in runnable?
public class TestThread implements Runnable{
@Autowired
public CarService carService;
public TestThread(List<Car> listcar) {
List<Car> listcar = new ArrayList<Car>();
//This works here
listcar = new java.util.ArrayList<Car>(carService.findAllServices(0, 10000));
for(int i=0;i<listcar.size();i++) {
System.out.println("The all car services in runnable constructor"+listcar.get(i).getName());
}
}
public void run() {
try {
runrun();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//This does not work
public void runrun() throws Exception {
List<Car> listcar = new ArrayList<Car>();
listcar = new java.util.ArrayList<Car>(carService.findAllServices(0, 10000));
for(int i=0;i<listcar.size();i++) {
System.out.println("The all car services in run method "+listcar.get(i).getName());
}
}
}
TestThreadCallController.java:
@Controller
public class TestThreadCallController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody void FindyourCarService() throws IOException{
TestThread th=new TestThread(listcar);
new Thread(th).start();
ApplicationContext context = new ClassPathXmlApplicationContext("test-Thread.xml");
TestThread th1 = (TestThread) context.getBean("TestThread");
new Thread(th1).start();
}
}
test-Thread.xml
bean initialization code:
<bean id="TestThread" class="com.test.thread.domain.TestThread">
</bean>