java - 何时以及如何在我的 Rest Api 中实例化 Spring Bean

标签 java spring rest spring-boot spring-bean

首先,我是 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/

相关文章:

php - ZEND Framework 2 RESTful Web 服务模板错误

java - MySQL 根据另一个表选择表中的值

java - org.apache.http.client-4.3.6 : java. lang.NoClassDefFoundError : org. apache.http.impl.conn.PoolingHttpClientConnectionManager

java - PowerMock PrepareForTest 注释导致 AmazonSQSClient 构造函数出现问题

java - 无法 Autowiring Spring Security 实现类

spring - 如何定义多个initBinder

rest - Marketo "Import Lead"失败,出现错误 610 找不到请求的资源

java - 如何在 Spring 中创建动态 DTO 而无需发送完整的 Payload

java - 在 Java 接口(interface)中添加新方法,因此它涉及对继承类的最小更改

java - 如何在 Spring 中查看 SOAP 请求的 XML 输出?