Reputation: 449
I have a simple spring app with one controller
@RestController
public class UserController {
// @Autowired
// UserServiceImpl userService;
@RequestMapping(value="/getUser", method = RequestMethod.GET)
public String getUser(){
// return userService.greetUser();
return "Hello user";
}
It works when I start it. If I uncomment @Autowired
and run with the first return statement using UserService
it also works.
My Service interface
@Service
public interface UserService {
String greetUser();
void insertUsers(List<User> users);
}
and implementation
@Service
public class UserServiceImpl implements UserService{
@Override
public String greetUser() {
return "Hello user";
}
}
But when I test it, the app falls with the following errors
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)}
The test class
@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"));
}
}
Also, if I remove
// @Autowired
// UserServiceImpl userService;
and run test with second return statement, the test execute without error. I understand that the problem is in the UserServiceImpl
, but I don't know what it is. What do I need to correct?
Upvotes: 0
Views: 202
Reputation: 5371
You should try to autowire your bean by an interface, not implementation
@Autowired
UserService userService;
And also you should remove @Service
from UserService
interface
Upvotes: 1