- 接口和實(shí)現(xiàn)類
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中綁定接口和實(shí)現(xiàn)類(具體原因查看
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
注解根據(jù)接口
注入實(shí)現(xiàn)對(duì)象
到需要使用
的地方
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();
}
}
- 根據(jù)
步驟2
的對(duì)象創(chuàng)建類似于接口的實(shí)現(xiàn)對(duì)象的容器
的東西,在容器中創(chuàng)建步驟3
的對(duì)象任斋,根據(jù)@Inject
注解把實(shí)現(xiàn)對(duì)象
注入到構(gòu)造方法參數(shù)中
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();
}
}