Spring IoC: identifier per request

127 Views Asked by At

I've created this bean in order to get a Supplier<String>:

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

As you can see, it's intented to only generate an straightforward identifier string.

Each time, it's called, a new identifier is supplied.

I'd like to change this behavior, in order to get the same generated identifier inside request scope. I mean, first time a request is reached, a new indentifier is generated. From then on, next calls no this Supplier has to return the first generated indentifier inside request scope.

Any ideas?

3

There are 3 best solutions below

0
lczapski On

As it was written in commentary, maybe something like below will work:

@Bean
@RequestScope
public Supplier<String> auditIdSupplier() {
    String val = String.join("-","KEY",UUID.randomUUID().toString());
    return () -> val;
}
0
Ben On

You need to configure a request scoped 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());
    }

And then inject it where appropriate with either field injection

@Component
public class MyClass {

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

or object factory

@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();
    }
0
Mark Bramnik On

This is my version:

@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class AuditIdPerRequest {
   private String key;

   @PostConstruct 
   public void calculateKey() {
      this.key = String.join(
        "-",
        "KEY",
        UUID.randomUUID().toString()
    );
   }

   public String getAuditId() {
      return this.key;
   }  
}