1. 简介
Google Guice 是一个轻量级的依赖注入框架,它支持Java 5或者更高版本的JDK。Noear Solon 也是一个轻量级的依赖注入框架,它支持Java 8或者更高版本的JDK
本文会通过一些例子来初步的认识一下 Guice 和 Solon 的区别,及互通性。
2. 添加依赖
guice
<dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency>
solon
<dependency> <groupId>org.noear</groupId> <artifactId>solon</artifactId> </dependency>
3. 基础用法对照
- (a) 注入
Guice 的项目代码样例(略过 logger 和 communicator 的来源)
public class Communication { @Inject private Logger logger; @Inject private Communicator communicator; public boolean sendMessage(String message) { return communicator.sendMessage(message); } public static void main(String[] args){ Injector injector = Guice.createInjector(); Communication comms = injector.getInstance(Communication.class) comms.sendMessage("软件质量保障"); } }
Solon 的项目代码样例(略过 logger 和 communicator 的来源)
@Component public class Communication { @Inject private Logger logger; @Inject private Communicator communicator; public boolean sendMessage(String message) { return communicator.sendMessage(message); } public static void main(String[] args){ Solon.start(Communication.class, args); Communication comms = Solon.context().getBean(Communication.class); comms.sendMessage("软件质量保障"); } }
- (b) 反向控制绑定
Guice。此模块实现将Communicator绑定到其默认实现类DefaultCommunicatorImpl上,在找到Communicator的地方都将注入Default CommunicatorImpl的实例。
public class BasicModule extends AbstractModule { @Override protected void configure() { bind(Communicator.class).to(DefaultCommunicatorImpl.class); } }
Solon。则通过在 DefaultCommunicatorImpl 类上,添加组件注解。
@Component public class DefaultCommunicatorImpl extneds Communicator{ }
- (c) by name 注入
Guice
@Inject @Named("DefaultCommunicator") Communicator communicator; @Override protected void configure() { bind(Communicator.class) .annotatedWith(Names.named("DefaultCommunicator")) .to(DefaultCommunicatorImpl.class); }
Solon
@Inject("DefaultCommunicator") Communicator communicator; @Component("DefaultCommunicator") public class DefaultCommunicatorImpl extneds Communicator{ }