Home > Back-end >  Sping-boot configuration-properties and service layer injection
Sping-boot configuration-properties and service layer injection

Time:12-29

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.

CodePudding user response:

There is no hard rule for this as in Spring Boot we can add @EnableConfigurationProperties at a class level with stereotype annotations.

As a part of good practices EnableConfigurationProperties or any configuration thing should be part of Configuration class of or main spring boot class so any developer can easily figure out those configuration instead of going any specific service class and then check.

In your case, yo can use @EnableConfigurationProperties annotation in conjunction with @SpringBootApplication annotation.

CodePudding user response:

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.

  • Related