java – Guice inject. GetInstance () – good practice?

Suppose I have two applications that share the same library The library contains common classes, such as Dao, utils, etc All content in the shared library is connected to Guice My two applications depend on this library, but they do not directly depend on Guice

______    ______    ______
|      |  |      |  |      |
| APP1 |->| LIB  |<-| APP2 |
'------'  '------'  '------'

I currently use something like this:

static <T> Utils.getInstanceOf (Class<T> type);

This is just a package:

injector.getInstance (Class<T> type);

However, the Guice document states:

So what is the best way to provide dependency injection for two applications without having to bind them manually in the Guice module?

Solution

There is no such way You fully accept Guice or do not use it, and explicitly pass your dependencies Well, construct your code in this way, so you will never create class dependencies directly, but pass them through constructors. It can also be called "dependency injection", but I'm sure that's not what you mean If you don't want to use Guice in your application, you won't get anything better than getInstance (), which is ugly, especially because you use static wrappers

Ideally, your library should provide one that can be used in your application through Guice The module installed by createinjector (), or on the other hand, the library should provide an injector instance. You can use createchildinjector () and provide application specific modules A slight modification to this approach is to pass application specific modules to the library so that they can be used to create the injector Recently, I have written Guice based API instead of using the last method to support any type of Di, and it works normally

Using Guice in a servlet or jersey environment is not difficult For example, the latter has out of the box integration with Guice (at least in version 1. X) Guice servlet extension is also very good and convenient Just try and see yourself

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
分享
二维码
< <上一篇
下一篇>>