0

I would like to update this sample code by using a lombok annotation. But I struggle to extract the registerCount initialization from the constructor, because it depends on the injected collectorRegistry bean.

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;
    private final UserDetailsService userDetailsService;
    private final Counter registerCount;

    public UpdateUserController(UserService userService, UserDetailsService userDetailsService, CollectorRegistry collectorRegistry) {
        this.userService = userService;
        this.userDetailsService = userDetailsService;
        registerCount = Counter.build()
                .name("register_count")
                .labelNames("domain_name", "domain_id")
                .help("Number of registrations")
                .register(collectorRegistry);
    }
...

Is this possible in Lombok?

(I understand Lombok is not the holy grail, but I would like to know if this is also possible when using a lombok annotation like @RequiredArgsConstructor)

TomDoes
  • 274
  • 1
  • 16
  • 1
    This might be relevant - [Is there a Lombok way to initialise a final field that is calculated from other fields?](https://stackoverflow.com/questions/47187111/is-there-a-lombok-way-to-initialise-a-final-field-that-is-calculated-from-other). But that will require you to have `CollectorRegistry` as an instance variable. – Thiyagu Aug 09 '23 at 12:16

1 Answers1

2

Based on your current design in that UserController is a singleton and it has a Counter, why don't you just make Counter a spring bean as well? That way, you don't need the special constructor? Something like this..

@Configuration
public class CounterConfigSample {

  /* Spring will auto-inject CollectorRegistry here*/
  @Bean
  public Counter registerCount(CollectorRegistry collectorRegistry) {
     return Counter.build()
                .name("register_count")
                .labelNames("domain_name", "domain_id")
                .help("Number of registrations")
                .register(collectorRegistry);

   }

}

Then in your UserController

 public UpdateUserController(UserService userService, UserDetailsService userDetailsService, Counter registerCount) {
        this.userService = userService;
        this.userDetailsService = userDetailsService;
        this.registerCount = registerCount;
    }
Hermann Steidel
  • 1,000
  • 10
  • 18
  • Exactly this is what I've done, now that I wanted to use the same counter in a different class as well. – TomDoes Aug 09 '23 at 14:00
  • @TomDoes Yes, you kinda went a little behind Spring's back trying to create your own Counter but that's ok, it happens :D . When working with Spring, I always think about my college days example..."A Car never produces its own Engine; it's always installed by the Factory". Unless you have a specific case, we always want to try to leverage Dependency Injection. – Hermann Steidel Aug 09 '23 at 14:04