Java 自动连线返回NullPointerException

Java 自动连线返回NullPointerException,java,spring,autowired,Java,Spring,Autowired,我有一个接口RestService和一个RestServiceImpl类,如下所示: //恢复服务: public interface RestService { public void printMessage(); } //RestServiceImpl: @Service public class RestServiceImpl implements RestService { public RestServiceImpl() { } public

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

//恢复服务:

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
    }
} 

我错过了什么

首先,确保整个spring基础架构都已插入,成为JUnit框架和spring之间的“桥梁”:

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

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

    @Autowired
    RestService restService;

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

首先,确保整个spring基础设施都已插入,这是JUnit框架和spring之间的“桥梁”:

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

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

    @Autowired
    RestService restService;

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

@RunWith(SpringRunner.class)
添加到
RestServiceTest
的顶部,将
@RunWith(SpringRunner.class)
添加到
RestServiceTest
的顶部,您缺少的是向我们显示测试配置。您是否遵循了中的所有步骤?您缺少的是向我们展示测试配置。你是否遵循了课程中的所有步骤?