当前位置:网站首页>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
边栏推荐
- JVM family (2) - garbage collection
- bye! IE browser, this route edge continues to go on for IE
- PMP Exam key summary VI - chart arrangement
- 组合模式(Composite Pattern)
- 桥接模式(Bridge)
- 接口自动化框架脚手架-利用反射机制实现接口统一发起端
- [NLP] this year's college entrance examination English AI score is 134. The research of Fudan Wuda alumni is interesting
- R语言plotly可视化:plotly可视化互相重叠的直方图(histogram)、在直方图的底部边缘使用geom_rug函数添加边缘轴须图Marginal rug plots
- Custom exception classes and exercises
- 谁知道在中信建投证券开户是不是安全的
猜你喜欢

接口自动化框架脚手架-利用反射机制实现接口统一发起端

Unity AssetBundle资源打包与资源加载

Au revoir! Navigateur ie, cette route Edge continue pour IE

mysql打不开,闪退

丢弃 Tkinter!简单配置快速生成超酷炫 GUI!

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

卸载oracle报错

Unity AssetBundle asset packaging and asset loading

DolphinScheduler使用系统时间

As shown in the figure, the SQL row is used to convert the original table of Figure 1. Figure 2 wants to convert it
随机推荐
卸载oracle报错
Unity 从服务器加载AssetBundle资源写入本地内存,并将下载保存的AB资源从本地内存加载至场景
Composite pattern
Wechat applet development log
bad zipfile offset (local header sig)
R语言使用car包中的avPlots函数创建变量添加图(Added-variable plots)、在图像交互中,在变量添加图中手动标识(添加)对于每一个预测变量影响较大的强影响点
Au revoir! Navigateur ie, cette route Edge continue pour IE
Multithreading concurrent parallel threaded process
TCP实战案例之即时通信、BS架构模拟
Redis sentinel cluster main database failure data recovery ideas # yyds dry goods inventory #
Settings of gift giving module and other custom controls in one-to-one video chat system code
解析:去中心化托管解决方案概述
Dbeaver installation and use tutorial (super detailed installation and use tutorial)
Custom exception classes and exercises
Cisco * VRF(虚拟路由转发表)
DolphinScheduler使用系统时间
云服务器MYSQL查询速度慢
Thread lifecycle
函数的分文件编写
The introduction of flink-sql-mysql-cdc-2.2.1 has solved many dependency conflicts?