Micronaut will produce a reflection-free bean and will also at compile time calculate the property paths to evaluate, greatly improving the speed and efficiency of loading @ConfigurationProperties
.
An example of a configuration class can be seen below:
@ConfigurationProperties Example
@ConfigurationProperties Example
import io.micronaut.context.annotation.ConfigurationProperties
import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank
@ConfigurationProperties('my.engine') (1)
class EngineConfig {
@NotBlank (2)
String manufacturer = "Ford" (3)
@Min(1L)
int cylinders
CrankShaft crankShaft = new CrankShaft()
@ConfigurationProperties('crank-shaft')
static class CrankShaft { (4)
Optional<Double> rodLength = Optional.empty() (5)
}
}
import io.micronaut.context.annotation.ConfigurationProperties
import java.util.*
import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank
@ConfigurationProperties("my.engine") (1)
@NotBlank (2)
var manufacturer = "Ford" (3)
@Min(1L)
var cylinders: Int = 0
var crankShaft = CrankShaft()
@ConfigurationProperties("crank-shaft")
class CrankShaft { (4)
var rodLength: Optional<Double> = Optional.empty() (5)
}
}
Once you have prepared a type safe configuration it can simply be injected into your objects like any other bean:
@ConfigurationProperties Dependency Injection
@ConfigurationProperties Dependency Injection
@Singleton
class EngineImpl implements Engine {
final EngineConfig config
EngineImpl(EngineConfig config) { (1)
this.config = config
}
@Override
int getCylinders() {
config.cylinders
}
String start() { (2)
}
}
@ConfigurationProperties Dependency Injection
@Singleton
class EngineImpl(val config: EngineConfig) : Engine {(1)
override val cylinders: Int
get() = config.cylinders
override fun start(): String {(2)
return "${config.manufacturer} Engine Starting V${config.cylinders} [rodLength=${config.crankShaft.rodLength.orElse(6.0)}]"
}
}
1 | Inject the EngineConfig bean |
2 | Use the configuration properties |
Supply Configuration
Supply Configuration
ApplicationContext applicationContext = ApplicationContext.run(
['my.engine.cylinders': '8'],
"test"
)
Vehicle vehicle = applicationContext
.getBean(Vehicle)
println(vehicle.start())
Supply Configuration
val map = mapOf( "my.engine.cylinders" to "8")
val applicationContext = ApplicationContext.run(map, "test")
val vehicle = applicationContext.getBean(Vehicle::class.java)
The above example prints: "Ford Engine Starting V8 [rodLength=6.0]"
For example creating a subclass of EngineConfig
with @ConfigurationProperties('bar')
will resolve all properties under the path .