@Autowired 自动注入空指针异常 ( 问题出现在了Junit单元测试 )

我用的Junit测试

写法如下:

@Component
public class Test_SSM {
    
    
    @Autowired
    private UserService userService;
    
    @Test
    public void show() {
    
    
        System.out.println(userService);
    }
}

然后调用测试show方法

输出为 null

只需这样改, 测试类上的两行注解

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( locations = "classpath:applicationContext.xml")
/*locations属性值 为 spring 配置文件路径*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( locations = "classpath:applicationContext.xml")
public class Test_SSM {
    
    
    @Autowired
    private UserService userService;
    
    @Test
    public void show() {
    
    
        System.out.println(userService);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39906884/article/details/84592354
今日推荐