初试Guice测试文件

public class Test {

 public static void main(String[] args) {
  MyModule module = new MyModule();// 定义注射规则
  Injector injector = Guice.createInjector(module);// 根据注射规则,生成注射者
  Client client = new Client();
  injector.injectMembers(client);// 注射者将需要注射的bean,按照规则,把client这个客户端进行注射
  System.out.println(injector.getInstance(MyService.class));
  System.out.println(injector.getInstance(MyService.class));
  System.out.println(injector.getInstance(MyService.class));
  System.out.println(injector.getInstance(MyService.class));
  System.out.println(injector.getInstance(MyService01.class));
  client.myMethod();
 }
}

import com.google.inject.Inject;

public class Client {
 MyService service;

 @Inject
 // 告诉容器,这里的service对象的引用,需要进行注入
 void setService(MyService service) { // 这里的方法名字可以任意定义
  this.service = service;
 }

 public void myMethod() {
  service.myMethod();
 }
}


你可能感兴趣的:(bean,Google)