Guice快速入门

Google Guice 用户指南 - Ⅱ:愿景 就像工厂模式一样,依赖注入其实也只是一种设计模式。其核心原则是将行为与依赖进行解耦。使用依赖性注入这种设计模式提高了代码的模块化和可测试性,而 Guice 框架使其易于编写。 阅读详情

0?wx_fmt=jpeg

Spring框架的依赖注入是家喻户晓的,但是在实际的开发中我们想使用便捷的依赖注入功能,但是又不想引入Spring框架的笨重和复杂性,该怎么办呢?

有了Google Guice,这个问题便简单了,首先在你的maven项目里引入

<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.0</version>
</dependency>

官方文档里给出的例子又臭又长,我不使用官方的例子,下面我们来写个最简单的HelloWorld

import javax.inject.Singleton;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

@Singleton
class HelloPrinter {

	public void print() {
		System.out.println("Hello, World");
	}

}

@Singleton
public class Sample {

	@Inject
	private HelloPrinter printer;

	public void hello() {
		printer.print();
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector();
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}
}

我们使用Guice创建了一个注射器Injector,然后从Injector拿到你想要的对象就可以了,Guice会自动装配依赖树。Guice的启动速度是很快的,在一个大型应用中,Guice装配所有的模块决不会超过1s。Guice是一个非常干净的依赖注入框架,框架除了依赖注入功能之外,没有任何其它非相关模块功能。

Guice里最常用的两个注解就是@Singleton和@Inject,Singleton表示构建的对象是单例的,Inject表示被标注的字段将使用Guice自动注入。在一般的项目中这两个注解一般可以完成90%以上的装配工作。

Guice需要实例化对象,请确保相应被实例化的对象有默认构造器。

当某个接口有多个实现时,我们使用@ImplementedBy注解在接口定义上,指定接口的具体实现类

import javax.inject.Singleton;
import com.google.inject.Guice;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.Injector;

@ImplementedBy(SimpleHelloPrinter.class)
interface IHelloPrinter {
	void print();
}

@Singleton
class SimpleHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Simple World");
	}

}

@Singleton
class ComplexHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Complex World");
	}

}

@Singleton
public class Sample {

	@Inject
	private IHelloPrinter printer;

	public void hello() {
		printer.print();
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector();
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}
}

如果我们不用Singleton标注,每次获取实例时,Guice会重新构造一个,这个会有反射构造器的性能损耗,在高性能场景下,请谨慎。

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

class HelloPrinter {

	private static int counter;

	private int myCounter;

	public HelloPrinter() {
		myCounter = counter++;
	}

	public void print() {
		System.out.printf("Hello, World %d\n", myCounter);
	}

}

public class Sample {

	@Inject
	private HelloPrinter printer;

	public void hello() {
		printer.print();
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector();
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
		sample = injector.getInstance(Sample.class);
		sample.hello();
		sample = injector.getInstance(Sample.class);
		sample.hello();
		sample = injector.getInstance(Sample.class);
		sample.hello();
	}
}

我们可以不使用@ImplementedBy注解,因为这样不优雅,谁会在定义接口的时候就能预知实现类的名称呢。我们可以使用Guice Module定义装配规则,它相当于Spring的XML文件,只不过它的装配规则都是使用代码定义的。你可能会辩解说代码定义怎么能比得上XML定义呢,其实Guice Module在一个大型项目中也是非常的简洁,一般只会占用几十行代码,Module里面配置的仅仅是特殊的专配规则。就规则的可读性而言,代码要比XML舒服的多。

import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

interface IHelloPrinter {
	void print();
}

@Singleton
class SimpleHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Simple World");
	}

}

@Singleton
class ComplexHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Complex World");
	}

}

class SampleModule extends AbstractModule {

	@Override
	protected void configure() {
		bind(IHelloPrinter.class).to(SimpleHelloPrinter.class);
	}

}

@Singleton
public class Sample {

	@Inject
	private IHelloPrinter printer;

	public void hello() {
		printer.print();
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new SampleModule());
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}

}

我们还可以使用@Named名称指令来指定依赖注入实现

import javax.inject.Named;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Names;

interface IHelloPrinter {
	void print();
}

@Singleton
class SimpleHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Simple World");
	}

}

@Singleton
class ComplexHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Complex World");
	}

}

class SampleModule extends AbstractModule {

	@Override
	protected void configure() {
		bind(IHelloPrinter.class).annotatedWith(Names.named("simple")).to(SimpleHelloPrinter.class);
		bind(IHelloPrinter.class).annotatedWith(Names.named("complex")).to(ComplexHelloPrinter.class);
	}
}

@Singleton
public class Sample {

	@Inject
	@Named("simple")
	private IHelloPrinter simplePrinter;

	@Inject
	@Named("complex")
	private IHelloPrinter complexPrinter;

	public void hello() {
		simplePrinter.print();
		complexPrinter.print();
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new SampleModule());
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}

}

我们不使用字段注入,改用构造器注入,如果我们需要在构造器里做一些特别的初始化工作

import javax.inject.Named;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Names;

interface IHelloPrinter {
	void print();
}

@Singleton
class SimpleHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Simple World");
	}

}

@Singleton
class ComplexHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Complex World");
	}

}

class SampleModule extends AbstractModule {

	@Override
	protected void configure() {
		bind(IHelloPrinter.class).annotatedWith(Names.named("simple")).to(SimpleHelloPrinter.class);
		bind(IHelloPrinter.class).annotatedWith(Names.named("complex")).to(ComplexHelloPrinter.class);
	}

}

@Singleton
public class Sample {

	@Named("simple")
	private IHelloPrinter simplePrinter;

	@Named("complex")
	private IHelloPrinter complexPrinter;

	@Inject
	public Sample(@Named("simple") IHelloPrinter simplePrinter, @Named("complex") IHelloPrinter complexPrinter) {
		this.simplePrinter = simplePrinter;
		this.complexPrinter = complexPrinter;
	}

	public void hello() {
		simplePrinter.print();
		complexPrinter.print();
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new SampleModule());
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}

}

还可以自动注入Set,Map容器,但是得首先加上扩展库

<dependency>
    <groupId>com.google.inject.extensions</groupId>
    <artifactId>guice-multibindings</artifactId>
    <version>4.0</version>
</dependency>

注入Set

import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.multibindings.Multibinder;

interface IHelloPrinter {
	void print();
}

@Singleton
class SimpleHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Simple World");
	}

}

@Singleton
class ComplexHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Complex World");
	}

}

class SampleModule extends AbstractModule {

	@Override
	protected void configure() {
		Multibinder<IHelloPrinter> printers = Multibinder.newSetBinder(binder(), IHelloPrinter.class);
		printers.addBinding().to(SimpleHelloPrinter.class);
		printers.addBinding().to(ComplexHelloPrinter.class);
	}

}

@Singleton
public class Sample {

	@Inject
	private Set<IHelloPrinter> printers;

	public void hello() {
		for (IHelloPrinter printer : printers) {
			printer.print();
		}
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new SampleModule());
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}

}

注入Map

import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.multibindings.MapBinder;

interface IHelloPrinter {
	void print();
}

@Singleton
class SimpleHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Simple World");
	}

}

@Singleton
class ComplexHelloPrinter implements IHelloPrinter {

	public void print() {
		System.out.println("Hello, Complex World");
	}

}

class SampleModule extends AbstractModule {

	@Override
	protected void configure() {
		MapBinder<String, IHelloPrinter> printers = MapBinder.newMapBinder(binder(), String.class, IHelloPrinter.class);
		printers.addBinding("simple").to(SimpleHelloPrinter.class);
		printers.addBinding("complex").to(ComplexHelloPrinter.class);
	}

}

@Singleton
public class Sample {

	@Inject
	private Map<String, IHelloPrinter> printers;

	public void hello() {
		for (String name : printers.keySet()) {
			printers.get(name).print();
		}
	}

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new SampleModule());
		Sample sample = injector.getInstance(Sample.class);
		sample.hello();
	}
}

在全世界都沉迷于复杂的Spring框架时,Guice无疑是一股清流,在炎热的夏天,它就像一杯冰爽的橙汁,让人畅快不已。

以上内容还不够看,请移步官方文档https://github.com/google/guice/wiki/GettingStarted

Google Guice入门教程:HelloWorld示例解析 Google Guice是Java编程语言中一个流行的依赖注入框架,它通过最小化依赖关系的配置和查找,简化了代码的编写。Guice使得开发者可以专注于业务逻辑的实现,而不必担心如何实例化对象或管理它们之间的依赖关系。通过模块化的配置,Guice支持清晰的依赖关系定义和灵活的依赖解析机制。本章将介绍Guice的历史、特点及其在现代Java应用中的重要性,为您揭开启用依赖注入之旅的第一步。// 示例:简单的Guice模块和绑定@Override// 使用Guice提供的Injector创建实例。 阅读详情

相关推荐

如何理解Apollo模型参考自适应控制MRAC

最近有了解到百度无人驾驶Apollo项目中的横向控制有用到MRAC(Model Reference Adaptive Control),于是便详细研究了一下这个控制方法,在此总结一下心得。 什么是MRAC MRAC控制系统的基本结构图如下所示: 它由两个环路组成,由控制器和受控对象组成内环,这一部分称之为可调系统,由参考模型和自适应机构组成外环。实际上,该系统是在常规的反馈控制回路上再附加一个参考模型和控制器参数的自动调节回路而形成。在该系统中,参考模型的输出或状态相当于给定一个动态性能指标,(通常,参考模

zmhzmhzm的博客 6480

Guice简明教程

Guice是Google开源的一个依赖注入类库,相比于Spring IoC来说更小更快。Elasticsearch大量使用了Guice,本文简单的介绍下Guice的基本概念和使用方式。 学习目标 概述:了解Guice是什么,有什么特点;快速开始:通过实例了解Guice;核心概念:了解Guice涉及的核心概念,如绑定(Binding)、范围(Scope)和注入(Injection

幸爷的博客 3913

STM32通过ESP8266连接机智云APP(第二讲,烧录固件并测试)

今天与大家分享STM32通过ESP8266连接机智云APP,并完成数据的上传下发第二讲。带大家一起烧录机智云固件到ESP8266并且将其通过机智云串口助手与APP进行测试。

qq_63267523的博客 1425

如何快速掌握 Google Guice:Java 依赖注入的终极指南

Guice(发音如"juice")是 Google 推出的轻量级 Java 依赖注入框架,专为 Java 8 及以上版本设计。通过自动化管理对象依赖关系,让开发者专注于业务逻辑而非对象创建细节。🎯 ## 什么是依赖注入? 依赖注入(Dependency Injection)是一种设计模式,核心思想是将对象的依赖关系从代码中分离出来,由外部容器负责注入。这解决了传统开发中硬编码依赖的问题,让代

gitblog_00054的博客 1055

Eureka自我保护机制

Eureka自我保护机制 默认情况下,当eureka server在一定时间内没有收到实例的心跳,便会把该实例从注册表中删除(默认是90秒),但是,如果短时间内丢失大量的实例心跳,便会触发eureka server的自我保护机制,比如在开发测试时,需要频繁地重启微服务实例,但是我们很少会把eureka server一起重启(因为在开发过程中不会修改eureka注册中心),当一分钟内收到的心跳数大量减少时,会触发该保护机制。可以在eureka管理界面看到Renews threshold和Renews(last

Soul_Ming的博客 543

DDR5 JEDEC标准简析:一次读懂DDR5的核心规范!

JEDEC,全称是,中文名称是「电子元件工程联合委员会」,它是全球权威的存储接口标准制定机构。我们常见的 DDR2、DDR3、DDR4、DDR5 都是它搞出来的。📌 JEDEC 就像存储接口界的“裁判+编剧”——规定谁该怎么跑,怎么演,怎么配合。

weixin_43199439的博客 2576

Google Guice 系列教程 - 基础实践

前言 Google Guice 是一个轻量级的依赖注入框架,它支持Java 5或者更高版本的JDK,得利于Java 5中提供的泛型 (Generics) 和注释 (Annotations) ,它可以使得代码类型安全 (type-safe) 。那么何时使用在代码中使用 Guice 进行注入呢?一般来说,如果在你的应用代码中业务对象 (Business Objects) 之间的关系或者依赖需要手...

weixin_30550271的博客 512

Dify使用教程3:Dify创建工作流

Dify使用教程3:Dify创建工作流 接着,我们连接下一个节点:“LLM”填入上下文变量为:result。这时候知识库就添加成功了。添加新节点:结束节点。

拥抱具身智能,昇腾Ascend C 5129

Guice 快速入门

Guice是谷歌推出的一个轻量级依赖注入框架,帮助我们解决Java项目中的依赖注入问题。如果使用过Spring的话,会了解到依赖注入是个非常方便的功能。不过假如只想在项目中使用依赖注入,那么引入Spring未免大材小用了。这时候我们可以考虑使用Guice。本文参考了Guice官方文档,详细信息可以直接查看Guice文档。基本使用引入依赖如果使用Maven的话,添加下面的依赖项。<dependency

乐百川 1万+

C#中通过Mapster实现轻量级高效对象映射器:从零到精通

本文介绍了.NET生态中高性能对象映射库Mapster的完整使用指南。从基础安装(通过NuGet包)到快速入门示例,展示了如何实现简单对象映射。进一步讲解了自定义映射规则、命名不一致属性的处理方式,以及如何在ASP.NET Core中集成Mapster服务。针对复杂场景,详细解析了嵌套对象映射的配置技巧,并提供了性能优化方案(如预编译映射器)和调试技巧(启用调试模式、捕获映射异常)。通过完整的代码实践,帮助开发者高效解决从基础到高级的对象映射需求。

墨夶的博客 742

Abaqus数据导出技巧:轻松处理大量XY数据

通过上述三种方法,我们可以解决Abaqus中大量XY数据导出的问题。无论是使用插件、编写Python脚本,还是利用Abaqus的内置报告功能,都可以帮助我们高效地处理数据。希望这篇博客能够帮助到你,提高你在Abaqus使用过程中的数据处理效率。

m0_62153576的博客 1918

Google Guice 快速入门

Guice是Google开源的一个依赖注入类库,相比于Spring IoC来说更小更快。Elasticsearch大量使用了Guice,本文简单的介绍下Guice的基本概念和使用方式 基本使用 1. 引入依赖 如果使用gradle的话,添加下列依赖 compile group: 'com.google.inject.extensions', name: 'guice-multibi...

小旋锋 的博客 849

深度解析 Android 开发工程师岗位:技术栈、职责与面试全攻略

本文深度剖析Android开发工程师职位要求,从核心技术栈到面试准备进行全面解读。关键点包括:1)掌握Kotlin语言特性和Jetpack组件;2)具备UI开发、性能优化和逆向分析能力;3)理解MVVM架构和Room数据库;4)熟悉常用工具链和开发流程。文章提供了详细的面试题库及解析,涵盖基础概念、UI优化、架构设计等方向,并给出职业发展建议:夯实基础、拓展技术广度、培养工程素养。旨在帮助开发者系统性地准备Android岗位求职,把握移动开发领域的技术趋势。

郑伟强dev的专栏 176

Guice学习(二) ------- 快速入门

这两篇博客基本囊括了Guice所有基本操作: https://blog.youkuaiyun.com/qq_24761191/article/details/79420410 https://blog.youkuaiyun.com/xxxlxy2008/article/details/89736544

zyz的博客 320

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Google Guice完整指南:掌握轻量级依赖注入框架的终极教程

Google Guice(发音为"juice")是谷歌推出的一款专为Java 8及以上版本设计的轻量级依赖注入框架。这款强大的工具能够显著简化Java应用程序的开发流程,让代码更加模块化、可测试且易于维护。无论你是刚接触依赖注入的新手,还是希望提升项目架构的资深开发者,Guice都能为你带来全新的开发体验。🚀 ## 什么是依赖注入?为什么选择Guice? 依赖注入是一种设计模式,它允许对象在

gitblog_00031的博客 963

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Sitebricks 快速入门指南

Sitebricks 快速入门指南 Sitebricks是一个旨在加速Web应用开发的轻量级平台,它侧重于早期错误检测、代码的低占用量以及快速迭代。借助Guice框架,它融合了符合Java编程习惯的简洁编码风格。本指南将带你深入了解Sitebricks的基本组件,通过以下三个关键部分展开: 1. 项目的目录结构及介绍 Sitebricks的仓库基于GitHub管理,其典型的目录结构展示了一款成熟J...

gitblog_00241的博客 803

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Guice依赖注入框架:现代Java开发的终极指南

Guice(发音为"juice")是Google推出的轻量级**依赖注入框架**,专为Java 8及以上版本设计。作为现代Java开发中不可或缺的工具,Guice通过简洁的注解驱动方式,彻底改变了传统Java应用的架构设计模式。 ## 🚀 什么是依赖注入及其重要性 依赖注入是一种设计模式,它让对象在创建时自动获得其依赖的其他对象。想象一下,你不再需要手动创建复杂的对象网络,而是让框架为你处理

gitblog_00507的博客 814

Google 开源的依赖注入库,比 Spring 更小更快!

点击上方“芋道源码”,选择“设为星标”管她前浪,还是后浪?能浪的浪,才是好浪!每天 8:55 更新文章,每天掉亿点点头发...源码精品专栏原创 | Java 2020 超神之路,很肝~...

芋艿V 156

Ninja框架入门指南:10分钟快速搭建你的第一个Java Web应用

如果你正在寻找一个**快速、稳定且高效的Java全栈Web框架**,那么Ninja框架绝对值得你关注。作为一款专为现代Web开发设计的Java框架,Ninja以其简洁的API、强大的功能和卓越的性能,让Java Web开发变得更加轻松愉快。无论你是Java新手还是经验丰富的开发者,这篇**完整的Ninja框架入门教程**都将帮助你快速上手。 ## 🚀 为什么选择Ninja框架? Ninja框

gitblog_00980的博客 1171

Google Guice入门教程06-Web & Servlet

3 Web 和 Servlet 3.1 快速开始 我们从一个例子开始Guice Web的开发。 首先准备我们的环境,由于是web开发,因此我们需要guice-servlet的jar包。log4j不是必须的,只是为了方便日志记录而已(Guice内部是使用jdk内部的logging包来完成日志记录的)。 必可避免的要在web.xml中都一些手脚,这里先配置一个filter吧。 <filter...

weixin_30892037的博客 214
下一篇: 如何解决Java线程池队列过饱问题
codehole_
博客等级 码龄7年 34粉丝 132原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值