当我运行这个线程时,我得到了这个结果,我不知道为什么
FirstThread正在运行
加载栏页
线程“Thread-0”中的异常java.lang.NullPointerException at com.sctrcd.multidsdemo.integration.threads.FirstThread.run(FirstThread.java:29)
代码,
package com.sctrcd.multidsdemo.integration.threads;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.sctrcd.multidsdemo.domain.bar.Bar;
import com.sctrcd.multidsdemo.integration.config.AppConfig;
import com.sctrcd.multidsdemo.integration.repositories.bar.BarPagingAndSortingRepository;
import com.sctrcd.multidsdemo.integration.repositories.bar.BarRepository;
@ContextConfiguration(classes =AppConfig.class,
loader=AnnotationConfigContextLoader.class)
public class FirstThread extends Thread {
@Autowired
BarPagingAndSortingRepository barPage;
public void run() {
System.out.println("FirstThread is running");
System.out.println("Loading bar page");
Page<Bar> bars=barPage.findAll(new PageRequest(0, 1, Direction.DESC, "id"));
System.out.println("Bar page loaded");
Bar bar=bars.getContent().get(0);
System.out.println("Creating bar");
System.out.println(bar.getId());
System.out.println();
//int a = 20;
Thread.currentThread().interrupt();
System.out.println("Interrupt");
}
public static void main(String args[]) {
FirstThread thread=new FirstThread();
thread.start();
}
}
答案 0 :(得分:0)
以调试模式运行程序并评估29行中的每个方法调用和变量。所以你会看到哪些是空的
由于此代码是从public static void main启动的 - 没有初始化任何Injection上下文,并且@Autowired注释不起作用,因此barPage为null。
在JUnit测试中,如果在Junit测试中有特殊的注释,它可以工作,它初始化了Spring上下文
看看这里:http://www.springbyexample.org/examples/intro-to-ioc-creating-a-spring-application.html
始终考虑一条规则。豆类只能在另一个豆子中注射(自动装配)。你的测试用例不是bean
答案 1 :(得分:0)
这是pagingAndSorting bean
package com.sctrcd.multidsdemo.integration.repositories.bar;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.sctrcd.multidsdemo.domain.bar.Bar;
public interface BarPagingAndSortingRepository extends PagingAndSortingRepository<Bar, Integer> {
}
答案 2 :(得分:0)
您的Main方法应该如此成功绑定到Spring上下文:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
BarPagingAndSortingRepository barPage = (BarPagingAndSortingRepository) context.getBean("barPage");
}
}