首先,我是 Spring Boot 的新手,所以请记住这一点。
我有一个 REST api,在其中我试图最大限度地减少对同一对象的数据库调用,并且我已经确定使用作用域为 Request 的 Spring Bean 就是我想要的。假设这是正确的,这就是我想要做的:
1) Controller 接收经过验证的 PhotoImportCommandDto
命令
PhotoCommandController
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> importPhoto(@Valid @RequestBody PhotoImportCommandDto command){
...
}
2) PhotoImportCommandDto
被验证。注意定制@UserExistsConstraint
它通过调用服务方法来验证用户是否存在于数据库中。
PhotoImportCommandDto
@Component
public class PhotoImportCommandDto extends BaseCommand {
@NotNull(message = "userId must not be null!")
@UserExistsConstraint
private Long userId;
...
}
我想做的是以某种方式设置在 @UserExistsConstraint
中验证的用户的 Spring Bean并在整个 Http 请求中可能调用的各种方法中引用它,但我不太确定如何做到这一点。由于我从未真正创建过自己的 Spring Bean,因此我不知道如何继续。我读过各种指南,例如 this ,但我仍然不知道如何在我的代码中实现它。
任何帮助/示例将不胜感激。
最佳答案
您可以使用@Bean
注释。
@Configuration
public class MyConfiguration {
@Bean({"validUser"})
public User validUser() {
User user;
//instantiate user either from DB or anywhere else
return user;
}
然后就可以获取到validUser了。
@Component
public class PhotoImportCommandDto extends BaseCommand {
@Autowired
@Qualifier("validUser")
private User validUser;
...
}
关于java - 何时以及如何在我的 Rest Api 中实例化 Spring Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45891649/