换了新公司,刚上班,发现他们项目都不用spring进行DI,用的是简洁的guice。
pom配置:
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.1.0</version>
</dependency>
代码示例:
log接口:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:36 * \* Description: * \ */
public interface LogService {
void log(String msg);
}
log实现类:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:37 * \* Description: * \ */
public class LogServiceImpl implements LogService {
@Override
public void log(String msg) {
System.out.println("------LOG:" + msg);
}
}
一个简单的业务接口:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:35 * \* Description: * \ */
public interface UserService {
void process();
}
简单的业务实现类:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:35 * \* Description: * \ */
public class UserServiceImpl implements UserService {
@Override
public void process() {
System.out.println("我需要的一些操作");
}
}
调用接口:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:38 * \* Description: * \ */
public interface Application {
void work();
}
实现类:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:38 * \* Description: * \ */
public class MyApp implements Application {
private UserService userService;
private LogService logService;
@Inject
public MyApp(UserService userService,LogService logService) {
this.userService = userService;
this.logService = logService;
}
@Override
public void work() {
userService.process();
logService.log("程序正常运行");
}
}
注入方式为在构造方法中,为方法添加inject注解。
另外,需要再代码中,手动指定接口和实现的关系:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:51 * \* Description: * \ */
public class MyAppModule extends AbstractModule {
/** * 调用AbstractModule类提供的一些方法来配置依赖关系 */
@Override
protected void configure() {
bind(LogService.class).to(LogServiceImpl.class);
bind(UserService.class).to(UserServiceImpl.class);
bind(Application.class).to(MyApp.class);
}
}
测试代码:
/** * \* Created: liuhuichao * \* Date: 2018/3/28 * \* Time: 上午9:55 * \* Description: * \ */
public class MyAppTest {
private static Injector injector;
@BeforeClass
public static void init() {
injector = Guice.createInjector(new MyAppModule());//通过配置类初始化guice
}
@Test
public void testMyApp() {
Application myApp = injector.getInstance(Application.class);
myApp.work();
}
}
原文链接:https://www.f2er.com/javaschema/282268.html