23

I've declared an object which gets instantiated on application start. I want to access it inside a controller, which is part of a plugin. I want to be able to use that plugin, but I can't seem to get past the first part -- finding the MyWebsocketConnection object. None of the examples show how to do this. I don't want to inject into the controller because I'm writing a plugin (I saw static examples of how to do that somewhere).

Global.scala, plugin application \app\Global.scala

object Global extends GlobalSettings {

  object MyWebsocketConnection {
    val logger = // return something that gets instantiated once, like websocket object for logging to ui
  }

  class MyWebsocketConnection {
    import MyWebsocketConnection.logger
  }

  override def onStart(app: Application) {
    Logger.info("Application has started...");
  }

}

My custom logging plugin controller:

MyLogger.Scala, plugin application \app\controllers\MyLogger.scala

object MyLogger {

  def info(message: String) = {
    // THIS CAN'T BE FOUND ?
    // MyWebsocketConnection.logger.send(message)
  }

}

So, from the Play! 2.0 app that references the plugin, I would (probably) do something like below, but I can't even get past the part before this:

MyFutureController.scala, another Play! application \app\controllers\MyFutureController.scala

object MyFutureController extends Controller {
  def someRandomMethod = Action {
    // Custom logging
    MyLogger.info("Here's my log message!");
    Ok("This documentation stinks!")
  }
}

2 Answers 2

32

There is also workaround #3: move your Global class to a package and specify its fully qualified name in application.conf file, like so:

global= my.packaged.Global

1
  • 2
    The default is application.global=.... You're right it should be global=... without the application.
    – samwize
    Oct 11, 2012 at 6:22
3

The problem is that your Global objects resides in default package. And in Java, classes from default package can't be referenced from other packages, they are accessible only within the same package (default).

I see two workarounds of this problem.

  1. Move MyWebsocketConnection to some named package (say config) so it can be accessible in your application.

    object MyLogger {
      def info(message: String) = {
      config.MyWebsocketConnection.logger.send(message)
      }
    }
    
  2. Move your whole application into single package (but it is a lot of pain)

    foo
      |--controllers
      |--models
      |--views
      |--Global.scala
    

    Then Global object will resides in foo package and will be accessible within application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.