gwt.gwtp.guice.使用步骤

  1. 接口和实现类
package com.wkh.guice.service;

public interface TestService {
   void test();
}
package com.wkh.guice.service.impl;

import com.wkh.guice.service.TestService;

public class TestServiceImpl implements TestService {
   public void test() {
       System.out.println(123);
   }
}
  1. 在guice中绑定接口和实现类(具体原因查看gwt.gwtp.guice.bind)
package com.wkh.guice.module;

import com.google.inject.AbstractModule;
import com.wkh.guice.service.TestService;
import com.wkh.guice.service.impl.TestServiceImpl;

public class TestModule extends AbstractModule {
   protected void configure() {
       bind(TestService.class).to(TestServiceImpl.class);
   }
}
  1. 通过@Inject注解根据接口注入实现对象需要使用的地方
package com.wkh.guice.inject;

import com.google.inject.Inject;
import com.wkh.guice.service.TestService;

public class TestInject {
   private TestService testService;

   @Inject
   public TestInject(TestService testService) {
       this.testService = testService;
   }

   public void test() {
       testService.test();
   }
}
  1. 根据步骤2的对象创建类似于接口的实现对象的容器的东西,在容器中创建步骤3的对象,根据@Inject注解把实现对象注入到构造方法参数中
package com.wkh.guice;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.wkh.guice.inject.TestInject;
import com.wkh.guice.module.TestModule;

public class TestUseModule {
   public static void main(String[] args) {
       Injector injector=Guice.createInjector(new TestModule());
       TestInject test= injector.getInstance(TestInject.class);
       test.test();

   }
}

猜你喜欢

转载自blog.csdn.net/weixin_33912445/article/details/87280221
GWT
今日推荐