GWT 客户端使用 Guice @Named 注解注入值的解决方案

GWT 客户端使用 Guice @Named 注解注入值的解决方案

本文旨在解决在 GWT 客户端代码中使用 Guice 的 @Named 注解进行依赖注入时遇到的问题。由于 GWT 客户端环境的特殊性,直接使用 Guice 注入静态值会引发错误,例如 “You are executing Names.named() in GWT code” 以及 “Binding requested for constant key… but no explicit binding was found”。本文将介绍两种解决方案:使用 AbstractginModule 在客户端绑定静态值,以及使用 GWT rpc 从服务器端获取动态值,从而规避客户端直接使用 Guice 的限制,实现依赖注入。

客户端静态值的注入:使用 AbstractGinModule

由于 GWT 客户端无法完整模拟 Java 环境,直接使用 Guice 的 @Named 注解进行注入会导致错误。解决这一问题的关键在于使用 AbstractGinModule 在客户端进行绑定。

以下是一个示例:

  1. 创建 Gin 模块:

    创建一个类继承 AbstractGinModule,并在 configure() 方法中进行绑定。

    import com.google.gwt.inject.client.AbstractGinModule; import com.google.inject.name.Names;  public class MyGinModule extends AbstractGinModule {   @Override   protected void configure() {     bindConstant().annotatedWith(Names.named("endpoint")).to("Endpoint URL");   } }
  2. 在 GWT 模块中引入 Gin 模块:

    在你的 GWT 模块的 *.gwt.xml 文件中,添加 Gin 模块的引用。

    <module rename-to='mymodule'>   <!-- Inherit the core Web Toolkit stuff.                        -->   <inherits name='com.google.gwt.user.User'/>    <!-- Inherit the Gin module.                                   -->   <inherits name="com.google.gwt.inject.Inject"/>    <!-- Other module settings... -->   <source path='client'/>   <entry-point class='com.example.client.MyEntryPoint'/> </module>
  3. 使用 @Inject 和 @Named 注解:

    在你的 GWT 客户端代码中,使用 @Inject 和 @Named 注解来注入值。

    import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.name.Named;  public class MyUIPanel extends Composite {    private static MyUIPanelUiBinder uiBinder = GWT.create(MyUIPanelUiBinder.class);    interface MyUIPanelUiBinder extends UiBinder<Widget, MyUIPanel> {   }    @Inject   @Named("endpoint")   private String endpoint;    @Inject   public MyUIPanel() {     initWidget(uiBinder.createAndBindUi(this));     // Use the injected endpoint value     GWT.log("Endpoint: " + endpoint);   } }

    注意: 你需要使用 Gin 来创建 MyUIPanel 的实例,而不是使用 new MyUIPanel()。 通常,你需要在你的 EntryPoint 中使用 GinInjector 来获取实例。

    import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.RootPanel; import com.google.inject.Guice; import com.google.inject.Injector;  public class MyEntryPoint implements EntryPoint {    @Override   public void onModuleLoad() {     Injector injector = Guice.createInjector(new MyGinModule());     MyUIPanel myUIPanel = injector.getInstance(MyUIPanel.class);     RootPanel.get().add(myUIPanel);   } }

客户端动态值的获取:使用 GWT RPC

对于需要从属性文件或数据库动态获取的值,不能直接在客户端使用 Guice 注入。 解决方案是将获取动态值的逻辑放在服务器端,然后通过 GWT RPC 将值传递给客户端。

以下是一个示例:

  1. 定义 RPC 服务接口:

    import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;  @RemoteServiceRelativePath("endpointService") public interface EndpointService extends RemoteService {   String getEndpoint(); }
  2. 定义 RPC 服务接口的异步版本:

    import com.google.gwt.user.client.rpc.AsyncCallback;  public interface EndpointServiceAsync {   void getEndpoint(AsyncCallback<String> callback); }
  3. 实现 RPC 服务接口:

    import com.google.gwt.user.server.rpc.RemoteServiceservlet;  public class EndpointServiceImpl extends RemoteServiceServlet implements EndpointService {    @Override   public String getEndpoint() {     // Logic to fetch endpoint from properties file or database     return "Dynamic Endpoint URL from Server";   } }
  4. 在 web.xml 中配置 Servlet:

    <servlet>   <servlet-name>endpointService</servlet-name>   <servlet-class>com.example.server.EndpointServiceImpl</servlet-class> </servlet> <servlet-mapping>   <servlet-name>endpointService</servlet-name>   <url-pattern>/mymodule/endpointService</url-pattern> </servlet-mapping>
  5. 在客户端调用 RPC 服务:

    import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget;  public class MyUIPanel {    public void loadEndpoint() {     EndpointServiceAsync endpointService = GWT.create(EndpointService.class);     ServiceDefTarget endpoint = (ServiceDefTarget) endpointService;     endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "endpointService");      endpointService.getEndpoint(new AsyncCallback<String>() {       @Override       public void onFailure(Throwable caught) {         GWT.log("Error fetching endpoint: " + caught.getMessage());       }        @Override       public void onSuccess(String result) {         // Use the endpoint value obtained from the server         GWT.log("Endpoint from server: " + result);       }     });   } }

总结

在 GWT 客户端使用 Guice 进行依赖注入需要注意其特殊性。 对于静态值,可以使用 AbstractGinModule 在客户端进行绑定。 对于动态值,建议使用 GWT RPC 从服务器端获取。 这样可以避免客户端直接使用 Guice 引起的错误,并保证应用程序的正常运行。

注意事项:

  • 确保正确配置 Gin 模块和 GWT RPC 服务。
  • 在开发模式下,可能需要配置 CORS 才能允许客户端从服务器获取数据。
  • 始终在服务器端进行敏感数据的处理,避免在客户端暴露敏感信息。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享