如何使用 Guice 重新初始化控制器中的注入组件?
How to reinitialize injected component in controller with Guice?
我有一个控制器:
public class MyController extends Controller {
private final AuthChecker authChecker;
@Inject
public MyController(AuthChecker authChecker) {
this.authChecker = authChecker;
}
public Promise<Result> index() throws BusinessException {
authChecker
.tokenValue(request().username())
.execute()
.go();
// bla bla bla
}
}
我对 AuthChecker
有疑问,因为它保留了一个内部状态,不会在每次请求之间重新初始化。这个 class 的初始化是在它的构造函数中完成的,它只执行一次,而不是 @Singleton
New instances are created every time a component is needed. If a
component is used more than once, then, by default, multiple instances
of the component will be created. If you only want a single instance
of a component then you need to mark it as a singleton.
我希望每个请求都告诉 Guice 创建一个新实例。
我该如何解决这个问题?
另外,控制器是单例的吗?因为它们似乎在整个应用程序生命周期中只被创建一次。
谢谢。
您可以使用 Provider,这意味着 guice 会在您每次访问它时创建一个新实例(如果您的模块中没有另外配置):
public class MyController extends Controller {
private final Provider<AuthChecker> authChecker;
@Inject
public MyController(Provider<AuthChecker> authChecker) {
this.authChecker = authChecker;
}
public Promise<Result> index() throws BusinessException {
authChecker.get()
.tokenValue(request().username())
.execute()
.go();
// bla bla bla
}
}
我有一个控制器:
public class MyController extends Controller {
private final AuthChecker authChecker;
@Inject
public MyController(AuthChecker authChecker) {
this.authChecker = authChecker;
}
public Promise<Result> index() throws BusinessException {
authChecker
.tokenValue(request().username())
.execute()
.go();
// bla bla bla
}
}
我对 AuthChecker
有疑问,因为它保留了一个内部状态,不会在每次请求之间重新初始化。这个 class 的初始化是在它的构造函数中完成的,它只执行一次,而不是 @Singleton
New instances are created every time a component is needed. If a component is used more than once, then, by default, multiple instances of the component will be created. If you only want a single instance of a component then you need to mark it as a singleton.
我希望每个请求都告诉 Guice 创建一个新实例。 我该如何解决这个问题?
另外,控制器是单例的吗?因为它们似乎在整个应用程序生命周期中只被创建一次。
谢谢。
您可以使用 Provider,这意味着 guice 会在您每次访问它时创建一个新实例(如果您的模块中没有另外配置):
public class MyController extends Controller {
private final Provider<AuthChecker> authChecker;
@Inject
public MyController(Provider<AuthChecker> authChecker) {
this.authChecker = authChecker;
}
public Promise<Result> index() throws BusinessException {
authChecker.get()
.tokenValue(request().username())
.execute()
.go();
// bla bla bla
}
}