首页 > 解决方案 > Spring IoC:每个请求的标识符

问题描述

我创建了这个 bean 以获得Supplier<String>

@Bean
public Supplier<String> auditIdSupplier() {
    return () -> String.join(
        "-",
        "KEY",
        UUID.randomUUID().toString()
    );
}

如您所见,它旨在仅生成一个简单的标识符字符串。

每次调用它时,都会提供一个新的标识符。

我想更改此行为,以便在请求范围内获得相同的生成标识符。我的意思是,第一次达到请求时,会生成一个新的标识符。从那时起, next 调用 no thisSupplier必须返回请求范围内的第一个生成的标识符。

有任何想法吗?

标签: springspring-ioc

解决方案


您需要配置一个请求范围的bean

@Configuration
public class MyConfig {

    @Bean
    @RequestScope
    public String myRequestScopedIdentifyer(NativeWebRequest httpRequest) {
        // You don't need request as parameter here, but you can inject it this way if you need request context

        return String.join(
          "-",
          "KEY",
          UUID.randomUUID().toString());
    }

然后在适当的地方使用任一现场注入注入它

@Component
public class MyClass {

    @Autowired 
    @Qualifier("myRequestScopedIdentifyer")
    private String identifier

或对象工厂

@Component
public class MyClass {

    public MyClass(@Qualifier("myRequestScopedIdentifyer") ObjectFactory<String> identifyerProvider) {
        this.identifyerProvider= identifyerProvider;
    }


    private final ObjectFactory<String> identifyerProvider;

    public void someMethod() {
        String requestScopedId = identifyerProvider.getObject();
    }

推荐阅读