我有一个带有一个控制器的简单弹簧应用程序
@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;
并使用第二个return语句运行test,测试执行时没有错误。我知道问题出在UserServiceImpl
,但我不知道它是什么。我需要纠正什么?
答案 0 :(得分:1)
您应该尝试通过接口自动装配bean,而不是实现
@Autowired
UserService userService;
此外,您应该从@Service
界面
UserService