Embedding java dependencies in javascript - when to use singletones

I am trying to figure out how to use dependency injection in Play Framework 2.4. I am familiar with the general principles, but I don’t really understand the implications for the design. My general reasoning was that the static methods in the controller classes are too similar to global variables, and this can easily cause thread safety problems, etc., and also contribute to poor design overall. Since Play now encourages the switch to dependency injection, I also have to switch.

What I am confused about is that it is good practice in this context. When I read the official Play docs, he briefly talks about dependency injection, and then quickly mentions the @Singleton annotation. And an accessible example ( http://www.typesafe.com/activator/template/play-guice ) talks about the same word, "WelcomeTextGenerator".

So I'm wondering if singleton objects should be used, as the examples show? If so, what is the advantage over older static methods? Are there specific types of objects (for example, controllers?) That need to be single-point, and are there any performance implications for not marking objects as single points?

+7
java dependency-injection singleton
source share
1 answer

So I'm wondering if singleton objects should be used, as the examples show? If so, what is the advantage over older static methods?

Injection injection is a method for combining an application. You write components that are not directly dependent on each other. Instead, you add components to each other. This way you can simply swap whole parts of your application without touching a single line of code. Dependency injection is especially useful when it comes to unit tests.

Compared to static methods, you can use all these fantastic OOP stuff. The question is mainly "what are the disadvantages of static methods?"

Are there specific types of objects (for example, controllers?) That need to be single-point, and are there any performance implications for not marking objects as single points?

Playback, or more specifically Guice, will create a new object when a dependency is introduced by default. Marking them as @Singleton will only create one object and reuse the same object for all injections. In other words: Singletons retain some object creation and garbage collection, but synchronization is required to initialize the object.

To answer the question of when to use @Singleton , usually ( source ):

  • stateful objects such as configuration or counters
  • objects that are expensive to build or search
  • objects that link resources, such as a database connection pool.

Guice offers extensive documentation . I highly recommend looking over for a while.

+6
source share

All Articles