这已经多次回答,但是我已经设置了所有注释,并且它似乎正确连线。
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", "apple@gmail.com");
User user = userService.findUserById(id);
assert user.getAddress() != null;
assert user.getEmail() != null;
assert user.getUsername() != null;
}
我试过在com.service和com.serviceImpl上的测试类中使用componentScan而没有运气。
完整错误:
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添加到main方法:
@SpringBootApplication
@ComponentScan("com.serviceImpl, com.service")
public class SpringCrudApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCrudApplication.class, args);
}
}
答案 0 :(得分:2)
必须通过ComnponentScan找到实现,而不是接口。 因此,如果您的类UserServiceImpl位于包com.serviceImpl中,则必须扫描此包。
包名称看起来很奇怪,包名称只能是小写。 因此,请尝试将程序包重命名为com.service.impl并扫描它。
因为您正在使用@Transactional,所以spring将创建一个实现UserService的代理。因此,您只能注入UserService但不能注册UserServiceImpl。 检查你的代码,可能是你试图在其他地方@Autowire一个UserServiceImpl。
除了您的异常'没有类型的匹配bean ...'之外,堆栈跟踪中通常会出现“无法自动装配”的消息, 春天试图注入什么类型。