spring-bootdependency-injectionconfigurationproperties

Sping-boot configuration-properties and service layer injection


I'm new to spring dependency-injection and am reaching out to learn about best practices. I would like to know if its a good design philosophy to inject classes annotated with @ConfigurationProperties into service layer classes (annotated with @Service). Im trying to map properties in my application.yml to a config-class as follows -

@ConstructorBinding
@ConfigurationProperties(prefix = "application")
class ApplicationConfig(
  val kafka: someDeeplyNestedType = SomeDeeplyNestedObj()
 ) {
       // helper functions
   }

I'm then injecting above config class in service layer as follows -

@Service
@EnableConfigurationProperties(ApplicationConfig::class)
class RestService(val config: ApplicationConfig) {
   init {
      // Reference config object
     // Reference application.yml properties via config object.
   }
}

I'm curious to know if I can improve upon my current implementation - not sure if its agreeable to pass configuration classes to service-layer classes. I'm also curious to know if theres any better approach to wiring ApplicationConfig without needing to use EnableConfigurationProperties annotation.


Solution

  • It is agreeable, documented, and probably "unrivaled" (only bounded by: "limitations" (no SpEL -> helper functions!?;)).

    To work with @ConfigurationProperties beans, you can inject them in the same way as any other bean, as shown in the following example:

    @Service
    public class MyService {
    
       private final SomeProperties properties;
       ...
    

    The only problems can arise from the "deeply", not "owning" the (config) structure ...and possibliy from "helper functions".

    But

    The prefix = "application" "sounds" suspicious!

    Note:

    [Most - almost All] (official) spring* boot properties, are already "typesafe", and have their object/class representation in spring-boot-autoconfigure packages.

    Please study that "typesafe chapter", but also gazing at PropertySource Abstraction.