Usage
Let’s walk through an example for configuring a Spring Boot application with Pkl.
For background information, see Externalized Configuration, in particular Type-safe Configuration Properties, in the Spring Boot documentation. |
-
Define a configuration schema in
src/main/resources
:AppConfig.pkl// this module name determines the package and // class name of the generated Java config class module samples.boot.AppConfig server: Server class Server { endpoints: Listing<Endpoint> } class Endpoint { name: String port: UInt16 }
-
Define an Application Property File next to the schema:
application.pklamends "modulepath:/appConfig.pkl" server { endpoints { new { name = "endpoint1" port = 1234 } new { name = "endpoint2" port = 5678 } } }
-
Use Pkl’s Gradle plugin to generate Java config classes from the schema. Generated classes are placed in
generated/configClasses/
and compiled together with your production code. To run the generator directly (which isn’t typically necessary), type./gradlew configClasses
.-
Groovy
-
Kotlin
build.gradleplugins { id "org.pkl-lang" version "$pklVersion" } pkl { javaCodeGenerators { configClasses { generateGetters.set(true) generateSpringBootConfig.set(true) sourceModules.set(files("src/main/resources/AppConfig.pkl")) } } }
settings.gradlepluginManagement { repositories { mavenCentral() } }
build.gradle.ktsplugins { id("org.pkl-lang") version "$pklVersion" } pkl { javaCodeGenerators { register("configClasses") { generateGetters.set(true) generateSpringBootConfig.set(true) sourceModules.set(files("src/main/resources/AppConfig.pkl")) } } }
settings.gradle.ktspluginManagement { repositories { mavenCentral() } }
-
-
Annotate your Boot application class with
@ConfigurationPropertiesScan
. (Alternatively, explicitly list configuration classes with@EnableConfigurationProperties(…)
.)@SpringBootApplication @ConfigurationPropertiesScan public class Application { ... }
-
Inject the generated config classes into your application’s components as appropriate.
@Service public class Server { public Server(AppConfig.Server config) { ... } }
-
To get access to the entire configuration, inject the
AppConfig
class itself:@Service public class Server { public Server(AppConfig config) { ... } }
This example demonstrates one way of configuring Spring Boot applications with Pkl. Some possible deviations are:
-
Use multiple config files, for example one per environment.
-
Read config files from the file system instead of the class path.
-
Write config classes by hand instead of generating them.
-
Do not define a config schema. (Config classes cannot be generated in this case.)
-
Use a build tool other than Gradle.
-
Declare a build dependency on
pkl-codegen-java
. -
Invoke the code generator’s
main
method during the build, passing the required arguments. -
Configure the build to compile generated config classes together with your production code.
-
For more information, see the Java code generator docs.
-