Play with framework Java dependency injection – when to use singletons

I tried to find out how to use dependency injection in play framework 2.4 I am familiar with general principles, but I don't really understand the impact on design My general reasoning is that static methods in controller classes are too similar to using global variables, and can easily lead to problems such as thread safety, and often encourage bad design Because play now encourages switching to dependency injection, I should also switch

What puzzles me is the good practice in this context When I read the official play documentation, it will briefly introduce dependency injection, and then mention the @ singleton annotation in time And examples available( http://www.typesafe.com/activator/template/play-guice )A single "welcometextgenerator" class is also discussed

So I want to know that I should use singleton objects, because what do these examples seem to mean? If this is the case, what are the advantages over the old static method? Is there a specific object type that should be a singleton (for example, controller?), Is there a performance impact of not marking objects as singletons?

Solution

Dependency injection is a technology that connects applications together The components you write are not directly interdependent Instead, the components are injected into each other In this way, you only need to swap the whole part of the application without touching any line of code Dependency injection is particularly useful when writing unit tests

You can use all that fancy OOP content compared to static methods The question is basically "what are the disadvantages of static methods?"

Play or more specifically, Guice creates a new object as long as dependencies are injected by default Marking them @ singleton will create only one object and reuse exactly the same object in all injections In other words: Singles save some object creation and garbage collection, but need synchronization to initialize objects

Solve the problem when using @ singleton based on your experience (source):

>Stateful objects, such as configuration or counters > construct or find expensive objects > objects bound to resources, such as database connection pools

Guice provides a very comprehensive documentation, by the way I strongly recommend browsing for a while

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>