- 接口和实现类
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);
}
}
- 在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);
}
}
- 通过
@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();
}
}
- 根据
步骤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();
}
}