@Autowired报空指针问题
今天碰到的这个问题其实蛮简单,只是太久没碰了,忘了。
今天简单搞了个代码想要,跑起来,代码如下:
测试类:
@SpringBootTest(classes = RApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Demo1 {
@Test
public void demoTest() {
Demo01 demo01 = new Demo01();
demo01.demo();
System.out.println("执行完成");
}
}
控制层:
@Controller
public class Demo01 {
@Autowired
private DemoService demoService;
public void demo() {
Employee byId = demoService.getById('1');
System.out.println(JSON.toJSONString(byId));
System.out.println("在ctroller中调用成功");
}
}
我刚开始想当然的直接new了个类,然后调用方法去执行。结果就报空了。
接下来我把改过来的代码放上来看看。
@SpringBootTest(classes = RApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
@Slf4j
public class Demo2 {
@Autowired
private Demo01 demo01;
@Test
public void test1() {
demo01.demo();
System.out.println("执行完成");
}
}
我想问题很直观的表现出来了吧。没错就是容器空间问题。你的service,controller都是放在spirng容器的,而Autowired也是在spring容器中进行依赖注入的。你这个时候去new一个新空间,当然会使demoService没有注入进来。