`

Google Guice学习一(基础)

 
阅读更多

Google Guice是依赖注解的DI容器,支持字段、方法和构造函数的注入依赖。

使用方法步骤为配置需要注入的字段、配置模板、使用Injector API获得实例。

 

 一、 支持的注入方式

1、字段注入

最常见的方式,使用@Inject注解完成

@Inject

private XmlUserLoader loader;

 

2、构造函数注入

@Inject

public XmlUserServiceImpl(XmlUserLoader loader)

{

this.loader=loader;

}

  3、setter方法注入

 

@Inject

public void setLoader(XmlUserLoader loader)

{

this.loader = loader;

}

 

  二、 注入的API(配置模板)

Guice通过配置Module的方式来绑定关系。

 

public class ClientModule implements Module
{

	public void configure(Binder binder)
	{
		binder.bind(UserService.class).to(XmlUserServiceImpl.class);
	}

}
 
Binder中提供了很多绑定的API,这些API其实可以理解为配置文件。支持很多种类型的绑定

 

1、绑定一个具体的子类:
binder.bind(UserService.class).to(XmlUserServiceImpl.class);

2、绑定一个实例:

binder.bind(UserService.class).toInstance(new XmlUserServiceImpl());

3、支持注解形式的绑定:

binder.bind(String.class).annotatedWith(Names.named("xmlUrl")).toInstance("/user.xml");

这样如果存在如下代码:

        @Inject

@Named("xmlUrl")

private String xmlUrl;

那么这个字符串将会设置为"/user.xml"

当然也可以设置自定义的注解。但是个人认为Names这个注解已经基本满足要求了。

可以看一下com.google.inject.name.Names.named(String)方法,其实返回的是个注解,类继承了注解。

class NamedImpl implements com.google.inject.name.Named, Serializable {

  private final String value;
           //com.google.inject.name.Named是个注解类型
  public NamedImpl(String value) {
    this.value = checkNotNull(value, "name");
  }

 

自定义注解的示例:

 

@Retention(RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@BindingAnnotation      //这个必须要加上才行,否则报错
public @interface English
{

}

 那么在Module中的使用如下:

public class Client
{
	@Inject
	@English
	private MyService service;

	public void greeting()
	{
		System.out.println(service.greeting());
	}

	public static void main(String[] args)
	{
		Module module = new Module()
		{
			public void configure(Binder binder)
			{
				binder.bind(MyService.class).annotatedWith(English.class).to(EnglishService.class);
			}
		};
		Injector i = Guice.createInjector(module);
		Client client = i.getInstance(Client.class);
		client.greeting();
	}
}

 4、provider形式的绑定

provider提供了更灵活的形式可以自定义创建对象的逻辑。框架提供了两种provider的形式。

A、实现provider接口,并绑定

修改上面示例如下:

final Provider<MyService> provider = new Provider<MyService>()
		{

			public MyService get()
			{
				// 用户的自定义创建逻辑
				return new EnglishService();
			}
		};

		Module module = new Module()
		{
			public void configure(Binder binder)
			{
				binder.bind(MyService.class).annotatedWith(English.class).toProvider(provider);
			}
		};

 

B、通过@Provides在Module中定义方法

 

	@Provides
        @Name("test")
	public MyService getMyService()
	{
		// 用户的自定义创建逻辑
		return new EnglishService();
	}

 5、静态类注入

对静态字段类注入:

	public void configure(Binder binder)
	{
		binder.bindConstant().annotatedWith(Names.named(("DataTimeUtils"))).to("yyyy-MM-dd");
		binder.requestStaticInjection(DataTimeUtils.class);
	}


@Inject
	@Named("DataTimeUtils")
	private static String dataFormat;

 6、不明确的注入:

通过ImplementedBy注解指定需要使用的类

@ImplementedBy(EnglishService.class)

public interface MyService

{

String greeting();

}

 

三、 使用Injector API获取实例

	Injector i = Guice.createInjector(new MyModule());
		Client client = i.getInstance(Client.class);   //直接获取实例
		client.greeting();

 

Client client = new Client();
		Injector i = Guice.createInjector(new MyModule());
		i.injectMembers(client);   //调用该API,填充字段
		client.greeting();

 

分享到:
评论

相关推荐

    google guice基础例子

    Guice是Google开发的一个轻量级,基于Java5(主要运用泛型与注释特性)的依赖注入框架(IOC)。Guice非常小而且快。Guice是类型安全的,它能够对构造函数,属性,方法(包含任意个参数的任意方法,而不仅仅是setter...

    guice入门学习资料

    guice 学习资料,快速掌握guice的编程技巧以及了解其机制。

    Google Guice与MyBatis集成,并实现发送邮件轮询

    Google Guice 这个高效的与Spring类似的依赖注入框架; MyBatis配置和使用; Google Guice与MyBatis集成,支持注解事务,简单的无法想象; Mybatis与mysql集成;实现发送邮件轮询; 源码是个web项目,里面有数据库的...

    google guice 3.0源码

    google guice 3.0源码,官方下载,帮助你更好理解google guice实现的原理

    google Guice 1.0 用户指南 中文

    用 Guice 写 Java Guice 1.0 用户指南 王咏刚 译 Guice (读作"juice")是超轻量级的,下一代的,为Java 5及后续版本设计的依赖注入容器。

    Learning Google Guice

    谷歌Guice开发英文文档,很详细,对开发很有帮助,可当成工具书使用!

    google-guice用户手册

    google-guice用户手册,据说和spring pk

    Google Guice需要的jar

    Google Guice需要的jar包: Guice-3.0.jar javax.inject.jar

    Google Guice: Agile Lightweight Dependency Injection Framework

    Google Guice: Agile Lightweight Dependency Injection Framework will not only tell you "how," it will also tell you "why" and "why not," so that all the knowledge you gain will be as widely applicable ...

    DI容器框架Google Guice与Spring框架的区别

    DI容器,例如spring,picoContainer,EJB容器等等 与Guice的不同

    Google Guice入世(转 附带一Guice1.0的简单测试代码)

    博文链接:https://avengerbevis.iteye.com/blog/69237

    Google guice

    NULL 博文链接:https://m635674608.iteye.com/blog/2090042

    guice.jar/guice.jar

    guice.jar guice.jar guice.jar guice.jar guice.jar guice.jar guice.jar

    Google的产品Guice

    用户指南 博文链接:https://hejianjie.iteye.com/blog/83374

    google-guice

    Guice (读作"juice")是超轻量级的,下一代的,为Java 5及后续版本设计的依赖注入容器。 &lt;br&gt;

    Guice中文文档

    Guice中文文档,介绍Guice的基本使用,适合初学者。

    guice-3.0-API文档-中英对照版.zip

    标签:google、inject、guice、jar包、java、API文档、中英对照版; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准...

    guice-multibindings-3.0-API文档-中文版.zip

    标签:google、inject、extensions、guice、multibindings、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变...

    guice-3.0-API文档-中文版.zip

    标签:google、inject、guice、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请...

Global site tag (gtag.js) - Google Analytics