Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Let's read config with custom types (see basic example at https://pastebin.com/1hFjBN1A)
- // TestController.scala
- import javax.inject.Inject
- import play.api.Configuration
- import play.api.mvc._
- class TestController @Inject()(
- cc: ControllerComponents,
- appConf: Configuration
- )extends AbstractController(cc) {
- val reportsName: Option[String] = appConf.get[Option[String]]("students.reports.name")
- val lastException: Option[Exception] = appConf.get[Option[Exception]]("students.reports.exception")
- // add to routes file: GET /testConfig controllers.TestController.testConfig
- def testConfig: Action[AnyContent] = Action(parse.json) {
- Ok(s"Name: $reportsName; Last error: $lastException")
- }
- }
- // application conf:
- students.reports {
- name = "qwerty"
- exception = "Smth not found"
- }
- // Compile output:
- // Error:(13, 72) could not find implicit value for parameter loader: play.api.ConfigLoader[Option[Exception]]
- // val lastException: Option[Exception] = appConf.get[Option[Exception]]("students.reports.exception")
- // We must create custom loader for java.lang.Exception type.
- // Let's create a loader for a common case: for our case class
- import javax.inject.Inject
- import com.typesafe.config.Config
- import play.api.{ConfigLoader, Configuration}
- import play.api.mvc._
- class TestController @Inject()(
- cc: ControllerComponents,
- appConf: Configuration
- ) extends AbstractController(cc) {
- case class MyConfig(reportsName: String, lastException: Exception)
- implicit val cfgLoader = new ConfigLoader[MyConfig] {
- override def load(config: Config, path: String): MyConfig = {
- val conf = config.getConfig(path)
- MyConfig(conf.getString("name"), new Exception(conf.getString("exception")))
- }
- }
- val myCfg: Option[MyConfig] = appConf.get[Option[MyConfig]]("students.reports")
- // add to routes file: GET /testConfig controllers.TestController.testConfig
- def testConfig: Action[AnyContent] = Action(parse.json) {
- Ok(s"Result: $myCfg")
- }
- }
- // Output:
- // http://localhost:9000/testConfig
- // Result: Some(MyConfig(qwerty,java.lang.Exception: Smth not found))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement