Advertisement
mitrakov

Scala Play: reading env

Jan 16th, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.54 KB | None | 0 0
  1. // 1. reading from application.conf
  2. import javax.inject.Inject
  3.  
  4. import play.api.Configuration
  5. import play.api.mvc._
  6.  
  7. class TestController @Inject()(cc: ControllerComponents, appConf: Configuration) extends AbstractController(cc) {
  8.  
  9.   val facultyName: Option[String] = appConf.get[Option[String]]("students.faculty.name") // also getString() is possible
  10.  
  11.   // add to routes file: GET    /testConfig    controllers.TestController.testConfig
  12.   def testConfig = Action {
  13.     Ok(s"Result: $facultyName")
  14.   }
  15. }
  16.  
  17. // application.conf:
  18. students {
  19.   faculty.name = "historical"
  20.   faculty.name = ${?FACULTY_NAME}
  21. }
  22.  
  23.         // Output:
  24.         // Result: Some(historical)
  25.  
  26. // 2. now set up environment variable: FACULTY_NAME=mathematics
  27.         // Result: Some(mathematics)
  28.  
  29. // 3. Bonus! What if we use ${FACULTY_NAME} instead of ${?FACULTY_NAME}?
  30. students {
  31.   faculty.name = ${FACULTY_NAME}
  32. }
  33.         // Output with environment variable defined:
  34.         // Result: Some(mathematics)
  35.  
  36.         // Output without environment variable:
  37.         // Internal server error, sending 500 response
  38.         // Configuration error: Configuration error[application.conf @ file:application.conf: 380:
  39.         // Could not resolve substitution to a value: ${FACULTY_NAME}]
  40.         //    at play.api.Configuration$.configError(Configuration.scala:155)
  41.         //    at play.api.Configuration$.load(Configuration.scala:101)
  42.         //    at play.api.Configuration$.load(Configuration.scala:109)
  43.         //    at play.api.Configuration$.load(Configuration.scala:115)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement