简体   繁体   中英

Scala and Slick: DatabaseConfigProvider in standalone application

I have an Play 2.5.3 application which uses Slick for reading an object from DB. The service classes are built in the following way:

class SomeModelRepo @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) {
  val dbConfig = dbConfigProvider.get[JdbcProfile]
  import dbConfig.driver.api._
  val db = dbConfig.db
  ...

Now I need some standalone Scala scripts to perform some operations in the background. I need to connect to the DB within them and I would like to reuse my existing service classes to read objects from DB.

To instantiate a SomeModelRepo class' object I need to pass some DatabaseConfigProvider as a parameter. I tried to run:

object SomeParser extends App {
    object testDbProvider extends DatabaseConfigProvider {
      def get[P <: BasicProfile]: DatabaseConfig[P] = {
        DatabaseConfigProvider.get("default")(Play.current)
      }
    }
    ...
    val someRepo = new SomeModelRepo(testDbProvider)

however I have an error: "There is no started application" in the line with "(Play.current)". Moreover the method current in object Play is deprecated and should be replaced with DI.

Is there any way to initialize my SomeModelRepo class' object within the standalone object SomeParser?

Best regards

When you start your Play application, the PlaySlick module handles the Slick configurations for you. With it you have two choices :

  1. inject DatabaseConfigProvider and get the driver from there, or
  2. do a global lookup via DatabaseConfigProvider.get[JdbcProfile](Play.current) , which is not preferred.

Either way, you must have your Play app running! Since this is not the case with your standalone scripts you get the error: "There is no started application".

So, you will have to use Slick's default approach, by instantiating db directly from config:

val db = Database.forConfig("default")

You have lot's of examples at Lightbend's templates .

EDIT: Sorry, I didn't read the whole question. Do you really need to have it as another application? You can run your background operations when your app starts, like here . In this example, InitialData class is instantiated as eager singleton , so it's insert() method is run immediately when app starts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM