自动装配将返回NullPointerException

时间:2018-09-22 14:55:38

标签: java spring autowired

我有一个接口RestService和一个RestServiceImpl类,如下所示:

// RestService:

public interface RestService {

    public void printMessage();
}

// RestServiceImpl:

@Service
public class RestServiceImpl implements RestService {

    public RestServiceImpl() {

    }

    public void printMessage() {
        System.out.println("This is a test message.");

    }

}

在测试printMessage()方法时,我收到一个NullPointerException。我很确定自己可以正确地自动接线,并且已经在类中添加了适当的注释。不知道为什么会这样。

@SpringBootTest
public class RestServiceTest {

    @Autowired
    RestService restService;

    @Test
    public void someTest() {
        restService.printMessage(); //Thows NullPointerException
    }
} 

我在这里想念什么?

2 个答案:

答案 0 :(得分:2)

首先,确保插入整个Spring基础结构,这是JUnit框架和spring之间的“桥梁”:

测试中没有@RunWith(SpringRunner.class)

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestServiceTest {

    @Autowired
    RestService restService;

    @Test
    public void someTest() {
        restService.printMessage(); //Thows NullPointerException
    }
}

答案 1 :(得分:0)

@RunWith(SpringRunner.class)顶部添加RestServiceTest