Spring MVC. Could not autowire for service

Делаю тесты для своего приложения на спринг, тестирую контролелер, не понимаю в чём ошибка. Подскажите, пожалуйста, в чём дело.

User service:

public interface UserService {

User register(User user);

User findByUsername(String username);

User update(User newUser, User oldUser);
}

User service impl:

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder;

@Autowired
public UserServiceImpl(
        final UserRepository userRepository,
        final BCryptPasswordEncoder passwordEncoder
) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
}
//далее просто перегрузка методов

Сам тест для контроллера:

@RunWith(SpringRunner.class)
@SpringBootTest
@Configuration
@EnableAutoConfiguration
public class TestUserRestController {

@MockBean
private UserRepository userRepository;

@Autowired
private UserService userService; // вот тут выдаёт ошибку

@Test
public void getByUserNameTest() throws Exception {
    User testUser = new User();
    testUser.setUsername("testLogin");
    testUser.setLastName("testLName");
    given(this.userRepository.findByUsername(any()))
            .willReturn(testUser);
    User user = userService.findByUsername(testUser.getUsername());
    assertEquals("testLName",user.getLastName());
}
}

В строке теста "@Autowired private UserService userService;" выдаёт ошибку:

Could not autowire. No beans of 'UserService' type found.

Подскажите, пожалуйста, в чём дело?


Ответы (1 шт):

Автор решения: Drakonoved

Нужно добавить имя бина для связывания (внедрения зависимости). Над классом сервиса и далее над тем полем (в контроллере), куда этот бин надо внедрить.

Service:

@Service
@Qualifier("userService")
@Slf4j
public class UserServiceImpl implements UserService {
. . .

Controller:

@Autowired
@Qualifier("userService")
UserService userService;

Но лучше это делать через конструктор:

UserService userService;

@Autowired
public TestUserRestController(@Qualifier("userService") UserService userService) {
    this.userService = userService;
}
→ Ссылка