Google Guice 與 Noear Solon 的簡單對照

带刺的坐椅發表於2024-10-29

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{
}

相關文章