這已經回答了好幾次,但我所有的註解集,它似乎正確佈線。型...發現依賴沒有匹配的豆....預期至少1 Bean上有資格作爲候選人自動裝配
UserService接口:
public interface UserService {
User findUserById(Long id);
User findUserByName(String name);
List<User> findAllUsers();
void saveUser(User user);
void updateUser(User user);
void deleteUserById(long id);
void deleteAllUsers();
public boolean isUserExist(User user);
}
UserServiceImpl
@Service
@Transactional
public class UserServiceImpl implements UserService {
private static final AtomicLong counter = new AtomicLong();
private static List<User> users;
static {
users = populateDummyUsers();
}
@Override
public User findUserById(Long id) {
for (User user : users) {
if (user.getId() == id) {
return user;
}
}
return null;
}
@Override
public User findUserByName(String name) {
for (User user : users) {
if (user.getUsername().equalsIgnoreCase(name)) {
return user;
}
}
return null;
}
測試用例這是失敗的:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringCrudApplication.class)
@ComponentScan("com.service")
public class ServiceTest {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Test
public void findUserByIdTest() throws Exception {
long id = (long) 0;
User userTest = new User(id,"Mike","644 Main St", "[email protected]");
User user = userService.findUserById(id);
assert user.getAddress() != null;
assert user.getEmail() != null;
assert user.getUsername() != null;
}
我曾嘗試使用componentScan在測試類上com.service和com.serviceImpl沒有運氣。
完整的錯誤:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'com.service.test.ServiceTest':
Unsatisfied dependency expressed through method 'setUserService'
parameter 0: No qualifying bean of type [com.service.UserService]
found for dependency [com.service.UserService]: expected at least 1
bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {}; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.service.UserService] found for
dependency [com.service.UserService]: expected at least 1 bean which
qualifies as autowire candidate for this dependency. Dependency
annotations: {}
------------------- SOLUTION ----------- --------
我不得不@ComponentScan添加到主方法:
@SpringBootApplication
@ComponentScan("com.serviceImpl, com.service")
public class SpringCrudApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCrudApplication.class, args);
}
}
我加了完整的錯誤。我在測試類和UserServiceImpl中使用了componentScan(「com.service」)。我還添加了我的目錄的屏幕截圖。 – Drew1208