Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play framework java dependency injection - when to use singletons

I am trying to work out how to use dependency injection in Play Framework 2.4. I am familiar with general principles, but don't really understand the implications for design. My general reasoning has been, static methods in controller classes are too much like using global variables, and that can easily cause issues with thread safety etc., plus in general encourage bad design. So since Play now encourages switching to dependency injection, I should switch as well.

What I am confused about is what good practice is in this context. When I read Play official docs, it talks briefly about dependency injection and then promptly mentions a @Singleton annotation. And and available example (http://www.typesafe.com/activator/template/play-guice) talks about a singleton "WelcomeTextGenerator" class as well.

So I am wondering, should I be using singleton objects as the examples seem to imply? If this is the case, what is the advantage compared to the old static methods approach? Are there specific object types (e.g., controllers?) that should be singletons, and are there performance implications to not marking objects as singletons?

like image 264
myrosia Avatar asked Jul 21 '15 17:07

myrosia


1 Answers

So I am wondering, should I be using singleton objects as the examples seem to imply? If this is the case, what is the advantage compared to the old static methods approach?

Dependency injection is a technique to wire together an application. You write components which do not directly depend on each other. Instead you inject the components to each other. This way you can simply exchange whole parts of your application without touching a single line of code. Dependency Injection is especially useful when it comes to write unit tests.

Compared to static methods you can use all that fancy OOP stuff. The question is basically "what are the disadvantages of static methods?"

Are there specific object types (e.g., controllers?) that should be singletons, and are there performance implications to not marking objects as singletons?

Play or more specifically Guice will create a new object whenever a dependency is injected by default. Marking them as @Singleton will create only one object, and reuse the exact same object on all injections. In other words: Singletons save some object creation and garbage collection, but require synchronization to initialize the object.

To come to your question when to use @Singleton, as a rule of thumb (source):

  • stateful objects, such as configuration or counters
  • objects that are expensive to construct or lookup
  • objects that tie up resources, such as a database connection pool.

Guice offers a very comprehensive documentation by the way. I highly recommend to browse through some time.

like image 118
Roman Avatar answered Sep 28 '22 04:09

Roman