gpt4 book ai didi

java - 正确使用 GWT RequestFactory ServiceLocator 和 DI

转载 作者:行者123 更新时间:2023-11-29 05:33:11 26 4
gpt4 key购买 nike

我是第一次尝试使用 RequestFactory (RF),并且正在努力实现我的第一个 ServiceLocator

来自RequestContext:

// Sign a user in or out of the app.
@ServiceName(
value="com.myapp.server.DefaultSignInOutService",
locator="com.myapp.server.DefaultSignInOutServiceLocator"
)
public interface SignInOutService extends RequestContext {
public Request<String> signIn(SignIn signIn);
public Request<Void> signOut(SignOut signOut);
}

然后是 DefaultSignInOutServiceLocator:

public class DefaultSignInOutServiceLocator implements ServiceLocator {
// I am using Guice-3.0 for server-side DI, and ServiceLocatorModule is an AbstractModule.
ServiceLocatorModule serviceLocatorModule = new ServiceLocatorModule();

// Will be initialized by Guice.
private DefaultSignInOutService signInOutService;

public DefaultSignInOutServiceLocator() {
super();

// Bootstrap DI.
Injector injector = GWT.createInjector(serviceLocatorModule);

// injector.getInstance() returns a fully-configured/wired
// DefaultSignInOutService instance.
setSignInOutService(injector.getInstance(SignInOutService.class));
}

@Override
public Object getInstance(Class<?> clazz) {
// I'm trying to use proper DI best practices here, and avoid code like:
//
// return new DefaultSignInOutService(true, "Yes", 35);
//
// Rather, I'd like to be able to return an already pre-configured service impl:
return signInOutService;
}

// Getters/setters, etc.
}

我的理解ServiceLocator基本上是服务实现的工厂。如果这是真的,那么如果我将 Guice 用于服务器端 DI,我需要从定位器的构造函数内部初始化我的 Guice 模块。但是,如果我需要自己编写任何代码(在应用程序的其他地方)来创建 DefaultSignInOutServiceLocator 实例并显式调用其 getInstance() 方法,那么我不需要将 ServiceLocatorModule 放在 DefaultSignInOutServiceLocator 中。在那种情况下,我可以有这样的代码:

public class DefaultSignInOutServiceLocator implements ServiceLocator {
@Injected
private DefaultSignInOutService signInOutService;

@Override
public Object getInstance(Class<?> clazz) {
return signInOutService;
}

// Getters/setters, etc.
}

所以这是我的问题:

  1. ServiceLocator 是否意味着放置 Guice 模块的适当位置(并因此从其中引导 DI)?否则,我如何才能为定位器注入(inject)正确连接/配置的服务实现?
  2. 或者,我只是不理解 ServiceLocator#getInstance() 的用途吗?
  3. 如果我在这里的方向是正确的,那么注入(inject)的 signInOutService 应该是什么“范围”(Spring DI 术语)?它应该是单例还是多例/原型(prototype)?我是否需要在这里担心线程安全(多个线程获得相同的 signInOutService 实例)?或者 GWT 是否以某种方式确保 RequestFactoryServlet 以线程安全的方式访问定位器?

最佳答案

ServiceLocatorServiceLayerDecorator 实例化,您可以插入自己的。

ServiceLocator 和它们创建的服务实例几乎是单例(如果可用内存不足,它们可以被垃圾收集,然后重新创建新实例),所以你应该将它们配置为你身边的单例,或者至少确保你这样对待它们(即注入(inject) Providers 用于请求范围的值,例如当前用户)。

您可以在 https://github.com/tbroyer/gwt-maven-archetypes 找到 Maven 原型(prototype)形式的完整示例

关于java - 正确使用 GWT RequestFactory ServiceLocator 和 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com