我有一个带有一个 Controller 的简单 Spring 应用程序
@RestController
public class UserController {
// @Autowired
// UserServiceImpl userService;
@RequestMapping(value="/getUser", method = RequestMethod.GET)
public String getUser(){
// return userService.greetUser();
return "Hello user";
}
当我启动它时它就起作用了。如果我取消注释 @Autowired
并使用 UserService
运行第一个 return 语句,它也可以工作。
我的服务界面
@Service
public interface UserService {
String greetUser();
void insertUsers(List<User> users);
}
和实现
@Service
public class UserServiceImpl implements UserService{
@Override
public String greetUser() {
return "Hello user";
}
}
但是当我测试它时,该应用程序出现以下错误
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
测试类
@RunWith(SpringRunner.class)
@WebMvcTest
public class DemoApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnHelloString() throws Exception{
this.mockMvc
.perform(get("/getUser"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("Hello user"));
}
}
另外,如果我删除
// @Autowired
// UserServiceImpl userService;
并使用第二个返回语句运行测试,测试执行没有错误。我知道问题出在 UserServiceImpl
中,但我不知道问题是什么。我需要纠正什么?
最佳答案
您应该尝试通过接口(interface)而不是实现来 Autowiring 您的 bean
@Autowired
UserService userService;
而且您还应该从 UserService
接口(interface)中删除 @Service
关于java - Spring Boot 应用程序在运行时可以运行,但在测试时会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44925280/