依赖注入框架Guice使用的简单例子
在Spring Boot实战一书中提到Spring可以更换依赖注入的框架,比如Google的Guice,所以了解一下Hello World怎么写
maven引入依赖
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.2</version>
</dependency>
代码:
/*
* Sample.java -- JDK 1.8
*/
package com.example.helloguice;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
@Singleton
public class Sample {
@Inject // Guice注入实现类的注解
private HelloPrinter printer;
public void hello() {
printer.print();
}
public static void main(String[] args) throws InterruptedException {
Injector injector = Guice.createInjector(); // 创建一个注射器
Sample sample = injector.getInstance(Sample.class);
System.out.println("Injecting...");
Thread.sleep(1000);
sample.hello();
}
}
@Singleton
class HelloPrinter {
public void print() {
System.out.println("Hello, World!");
}
}
posted on 2019-06-14 16:11 jinzhaoshi 阅读(143) 评论(0) 编辑 收藏 举报