如何使用 guice 绑定到 Web 应用中的每个请求中的不同实现



我已经为一组特定的请求设置了一个过滤器,即通过我的Guice监听器发送*/dispatch。

在此过滤器中,我想根据请求 URI 更改每个请求中类型BaseService(包含一个方法的接口)的绑定。 即如果URI是/hello/dispatch,我希望BaseService绑定到HelloServiceImpl,否则如果URI是/bye/dispatch,我想绑定到ByeServiceImpl。两者都实现了基本服务。

现在,在参与 servlet 请求处理的一个随机类中的某个地方,我想注入特定于当前请求的 BaseService 的适当实现。

这可能吗?如何?提前谢谢你。

考虑使用工厂模式来提供不同类型的 BaseService。

public interface ServiceFactory
{
  public BaseService create(String uri);
}
public class ServiceFactoryImpl implements ServiceFactory
{
  @Override
  public BaseService create(String uri)
  {
    if(uri.equals("/hello/dispatch"))
      return new HelloServiceImpl();
    else if (uri.equals("/bye/dispatch"))
      return new ByeServiceImpl();
    return null;
  }
}

然后是模块中的工厂。

bind(ServiceFactory.class).to(ServiceFactoryImpl.class);

并将其注入到请求中。

最新更新