当前位置:网站首页>Google open source dependency injection framework Guice Guide
Google open source dependency injection framework Guice Guide
2022-06-28 10:10:00 【Software quality assurance】
Continue to adhere to the original output , Click on the blue word to follow me
author : Software quality assurance
You know :https://www.zhihu.com/people/iloverain1024
I've posted an article before 《 On the implementation of dependency injection 》, The implementation principle of dependency injection is introduced . The article mentions tools for efficient implementation of dependency injection Guice, This article introduces this Google Open source dependency injection framework Guice And how to use it .
1. brief introduction
Google Guice Is a lightweight dependency injection framework , It supports Java 5 Or later JDK, Benefit from Java 5 Generics provided in (Generics) Annotation (Annotations) , It makes code type safe (type-safe) . So when to use in code Guice What about injection ? Generally speaking , If you have business objects in your application code (Business Objects) If the relationship or dependency needs to be maintained , You can use it Guice For injection .
This article will give a preliminary understanding through some examples Guice frame .
Of course , Students who do not understand the basic knowledge of dependency injection suggest reading this popular science post first 《 On the implementation of dependency injection 》.
2. Add dependency
Add the following dependencies to Maven Put... In the project pom.xml in :
<dependency><groupId>com.google.inject</groupId><artifactId>guice</artifactId><version>4.1.0</version></dependency>
3. Guice Basic usage
3.1 Project sample code
I still use the example in the previous article as a demonstration scenario , That is, take the three communication modes in real life as an example :Email、SMS and IM.
First , We define Communication class :
public class Communication {@Injectprivate Logger logger;@Injectprivate Communicator communicator;public Communication(Boolean keepRecords) {if (keepRecords) {System.out.println("Message logging enabled");}}public boolean sendMessage(String message) {return communicator.sendMessage(message);}}
This Communication Class is the communication base class , An example of this class implements sending messages through available communication channels . As shown in the above code ,Communication Will depend on Communicator, We call it to do the actual message transfer .
Guice The most basic usage is through Injector Object implementation , The following is an example of client code :
public static void main(String[] args){Injector injector = Guice.createInjector();Communication comms = injector.getInstance(Communication.class)comms.sendMessage(" Software quality assurance ");}
Guice Adopt a code first strategy for dependency injection and management , So we don't have to deal with a lot of crazy XML To configure .
3.2. Guice bind
Binding is to Guice as wiring is to Spring. adopt bind, We can do that Guice How to inject dependencies into a class ,
We are com.google.inject.AbstractModule Defined in the implementation of :
public class BasicModule extends AbstractModule {@Overrideprotected void configure() {bind(Communicator.class).to(DefaultCommunicatorImpl.class);}}
This module implementation will Communicator Bind to its default implementation class DefaultCommunicatorImpl On , Find Communicator All the places will be filled with Default CommunicatorImpl Example .
3.3. @Named annotation
We can use @Named Annotation to name these entity classes , When you give it a name , It will return a named Annotation. In the example above , have access to Names.named() To do the same thing .
@Inject @Named("DefaultCommunicator")Communicator communicator;
@Overrideprotected void configure() {bind(Communicator.class).annotatedWith(Names.named("DefaultCommunicator")).to(DefaultCommunicatorImpl.class);}
Use @Named(“DefaultCommunicator”) The annotation will Communicator Bound to the DefaultCommunicator Implementation class .
3.4. Constructor binding
We can also use constructor binding to inject a dependent object without a default parameterless constructor :
public class BasicModule extends AbstractModule {
@Override protected void configure() {
bind(Boolean.class).toInstance(true); bind(Communication.class).toConstructor( Communication.class.getConstructor(Boolean.TYPE));}Another method of constructor binding is instance binding , We are directly responsible for Communication.class Bind an instance :
public class BasicModule extends AbstractModule {@Overrideprotected void configure() {bind(Communication.class).toInstance(new Communication(true));}}
No matter where we state Communication class , This binding will provide Communication Class . But in this case , The dependency tree of a class is not automatically associated .
4. Dependency injection type
Guice Support DI Recommended standard injection type . Suppose that Communicator Class , We need to inject different types of CommunicationMode, This can be achieved in the following ways .
4.1 Attribute injection
@Inject @Named("SMSComms")CommunicationMode smsComms;
We can use @Named Annotations are used as qualifiers to implement name based directed injection .
4.2. Method Inject
Here we will use a setter Method to implement injection :
@Injectpublic void setEmailCommunicator(@Named("EmailComms") CommunicationMode emailComms) {this.emailComms = emailComms;}
4.3. Constructor injection
We can also inject dependencies using constructors :
@Injectpublic Communication(@Named("IMComms") CommunicationMode imComms) {this.imComms= imComms;}
4.4. Implicit injection
Guice It also provides implicit injection of some common components , for example Injector and java.util.Logger Examples of . Did you find out , All our examples use Logger, But you can't find the actual binding code .
5. Guice Scope Mechanism
Guice Support us in other DI Getting used to in the framework Scope and Scope Mechanism .
5.1 Single case
Let's inject a singleton into our application , We have designated Communicator Of Scope, It will be marked as a singleton instance .
bind(Communicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(Communicator.class).in(Scopes.SINGLETON);
5.2. Hungry han singleton
Let's inject a starving Han style singleton ,asEagerSingleton() Method to mark the singleton pattern .
bind(Communicator.class).annotatedWith(Names.named("AnotherCommunicator")).to(Communicator.class).asEagerSingleton();
Like it , Just click on it. Zanhe is looking at Let's go
- END -
Scan the code below to pay attention to Software quality assurance , Learn and grow with quality gentleman 、 Common progress , Being a professional is the most expensive Tester!
The background to reply 【 Test open 】 Get test development xmind Brain map
The background to reply 【 Add group 】 Get to join the testing community !
Previous recommendation
Talk to self-management at work
Experience sharing | Test Engineer transformation test development process
Chat UI Automated PageObject Design patterns
边栏推荐
- Django database operation and problem solving
- Why does istio use spirit for identity authentication?
- ECS MySQL query is slow
- 优秀笔记软件盘点:好看且强大的可视化笔记软件、知识图谱工具Heptabase、氢图、Walling、Reflect、InfraNodus、TiddlyWiki
- 谁知道在中信建投证券开户是不是安全的
- 老板叫我写个APP自动化--Yaml文件读取--内附整个框架源码
- [Unity][ECS]学习笔记(三)
- 接口自动化框架脚手架-利用反射机制实现接口统一发起端
- Unity AssetBundle资源打包与资源加载
- [happy Lantern Festival] guessing lantern riddles eating lantern festival full of vitality ~ (with lantern riddle guessing games)
猜你喜欢

为什么 Istio 要使用 SPIRE 做身份认证?

Resolution: overview of decentralized hosting solution

如图 用sql行转列 图一原表,图二希望转换后

dotnet 使用 Crossgen2 对 DLL 进行 ReadyToRun 提升启动性能

fastposter v2.8.4 发布 电商海报生成器

Function sub file writing

Starting from full power to accelerate brand renewal, Chang'an electric and electrification products sound the "assembly number"
![[Unity]内置渲染管线转URP](/img/a5/3ae37b847042ffb34e436720f61d17.png)
[Unity]内置渲染管线转URP

Unity AssetBundle资源打包与资源加载

Dbeaver installation and use tutorial (super detailed installation and use tutorial)
随机推荐
Methods for creating multithreads ---1 creating subclasses of thread class and multithreading principle
Flip CEP skip policy aftermatchskipstrategy Skippastlastevent() matched no longer matches the Bikeng Guide
Please consult me. I run the MYSQL to MySQL full synchronization of flykcdc in my local ide. This is in my local ide
Is it safe to open an account with the QR code of CICC securities? Tell me what you know
dotnet 使用 Crossgen2 对 DLL 进行 ReadyToRun 提升启动性能
增量快照 必须要求mysql表有主键的吗?
Cisco * VRF(虚拟路由转发表)
布隆过滤器 课程研究报告
ECS MySQL query is slow
As shown in the figure, the SQL row is used to convert the original table of Figure 1. Figure 2 wants to convert it
爬虫小操作
Bridge mode
老板叫我写个APP自动化--Yaml文件读取--内附整个框架源码
June 27, 2022: give a 01 string with a length of N. now please find two intervals so that the number of 1 is equal and the number of 0 is equal in the two intervals. The two intervals can intersect bu
PMP examination key summary VIII - monitoring process group (2)
手机号、邮箱正则验证[通俗易懂]
第三章 栈和队列
Resolution: overview of decentralized hosting solution
How to distinguish and define DQL, DML, DDL and DCL in SQL
Dolphin scheduler uses system time