我有一个用户控制器。
用户控制器:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("users")
public class UserRestController {
private final UserService userService;
public UserRestController(final UserService userService) {
this.userService = userService;
}
@GetMapping()
public User getInfo(
final @AuthenticationPrincipal UserDetails userDetails
) {
return userService.findByUsername(userDetails.getUsername());
}
@PutMapping()
public User update(
final @AuthenticationPrincipal UserDetails userDetails,
final @RequestBody User user
) {
User userInSystem = userService.findByUsername(
userDetails.getUsername()
);
return userService.update(user, userInSystem);
}
}
我为他做些测试。
测试用户控制器:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationArguments.class)
@Configuration // this annotation can be removed, the error will remain the same
@EnableAutoConfiguration //previous comment
public class TestUserRestController {
@Autowired
private UserRestController userRestController;
@Test
public void Test() {
assertThat(userRestController).isNotNull();
}
}
最后,运行测试时出现错误:
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ com.daniil.ostrouh.notes.TestUserRestController”的bean时出错:通过字段“ userRestController”表示的不满意依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为'com.daniil.ostrouh.notes.rest.UserRestController'的合格Bean:预计至少有1个有资格作为自动装配候选的Bean。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}
请告诉我我在做什么错
更新 项目结构:Project Structure
答案 0 :(得分:0)
每个标准的Spring Boot应用程序都应具有一个用@SpringBootApplication
注释注释的生产类。这个注释做了很多事情,包括向Spring发出有关组件扫描根目录的信号。组件扫描用于自动检测Spring Bean(@Component
,@RestController
等)。 @SpringBootTest
尝试自动检测是否为空的类为classes
。如果classes
有任何值,那么Spring上下文将仅包含指定的类(在这种情况下,ApplicationArguments
在这里不执行任何操作)。
因此,您应该从classes
中删除@SpringBootTest
,并且由于组件扫描使用此层次结构,因此应按层次结构对程序包进行结构化。
如果您需要更多帮助,请发布您的项目。