当前位置:网站首页>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
边栏推荐
- Dear leaders, ask me if MySQL does not support early_ Offset mode? Unsupported star
- Dbeaver installation and use tutorial (super detailed installation and use tutorial)
- Comprehensive evaluation of outline note taking software workflow: advantages, disadvantages and evaluation
- Function sub file writing
- Wechat applet development log
- The introduction of flink-sql-mysql-cdc-2.2.1 has solved many dependency conflicts?
- 卸载oracle报错
- JSON数据与List集合之间的正确转换
- Redis sentinel cluster main database failure data recovery ideas # yyds dry goods inventory #
- Starting from full power to accelerate brand renewal, Chang'an electric and electrification products sound the "assembly number"
猜你喜欢

老板叫我写个APP自动化--Yaml文件读取--内附整个框架源码

sqlcmd 连接数据库报错

Unity AssetBundle资源打包与资源加载

Instant messaging and BS architecture simulation of TCP practical cases

接口自动化框架脚手架-参数化工具的实现

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

Unity AssetBundle asset packaging and asset loading

Dolphin scheduler uses system time

HDI blind hole design, have you noticed this detail?

What is the best way to learn machine learning
随机推荐
MySQL的开发环境和测试环境有什么区别??
Multithreading concurrent parallel threaded process
爬虫小操作
How to distinguish and define DQL, DML, DDL and DCL in SQL
Must the MySQL table have a primary key for incremental snapshots?
Ideal interface automation project
组合模式(Composite Pattern)
[Unity][ECS]学习笔记(三)
Dotnet uses crossgen2 to readytorun DLL to improve startup performance
最小栈<难度系数>
Django数据库操作以及问题解决
Thread lifecycle
What is the best way to learn machine learning
Resolution: overview of decentralized hosting solution
[Unity]内置渲染管线转URP
Install using snap in opencloudos NET 6
优秀笔记软件盘点:好看且强大的可视化笔记软件、知识图谱工具Heptabase、氢图、Walling、Reflect、InfraNodus、TiddlyWiki
手机号、邮箱正则验证[通俗易懂]
为什么 Istio 要使用 SPIRE 做身份认证?
Restful style