@Autowired automatically injects a null pointer exception (the problem occurs in the Junit unit test)

I used Junit test

It is written as follows:

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

Then call the test show method

Output is null

Just change it like this, two lines of annotations on the test class

@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);
    }
}

Guess you like

Origin blog.csdn.net/qq_39906884/article/details/84592354