Apache Wicket:在表单验证器中注入依赖项(使用Guice) [英] Apache Wicket: Injecting dependencies in form validators (using Guice)
问题描述
我需要使用我的表单验证器之一访问数据库服务层(以确保注册新用户时电子邮件尚未被接收) )。
I need to access the DB service layer in one of my form validators (to make sure the email is not already taken when registering a new user).
我尝试了以下操作(为简便起见,省略了一些输入字段):
I tried the following (some input-fields omitted for brevity):
public class RegistrationPage extends WebPage {
@Inject
private UserService userService;
public RegistrationPage() {
add(new FeedbackPanel("feedback"));
TextField<String> email = new TextField<String>("email", Model.of(""));
...
email.add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
String email = validatable.getValue();
if (userService.findUserByEmail(email) != null) {
// report error...
}
}
});
Form<?> form = new Form<Void>("registrationForm") { ... };
form.add(email);
add(form);
}
}
不幸的是,这可能会导致
This can unfortunately result in a
java.lang.IllegalStateException: EntityManager is closed
我怀疑这个问题是由于我使用的是开放会话视图,并且多个表单提交跨越了多个请求。 userService
为第一个请求注入,并(非法)在后续请求中重用。 (如果验证失败,并且用户尝试再次提交表单,则会提交多个表单。)
I suspect that the problem is due to the fact that I'm using open-session-in-view and that multiple form-submissions span over several requests. The userService
is injected for the first request and (illegally) reused in subsequent requests. (Multiple form-submissions happen if the validation fails and the user attempts to submit the form again.)
解决此问题的最佳方法是什么?与我解决上一个问题的方法相同,类似的问题?在这种情况下,无疑会变得更加混乱。
What is the best way to solve this? The same way as I solved the previous, similar problem? It will undoubtedly get messier in this case.
推荐答案
您需要和检票口使用不同的生命周期。
There is a bit different lifecycle that you want and that wicket uses.
首先考虑一下,了解Wicket组件的实例化和注入:
First think first, understand Wicket component instantion and injection:
- 实例组件
- 调用注入器-
IComponentInstantionListener.onInstantiation(组件组件) - 注入带注释的字段
- 使用组件(呈现等)
- 下一个请求-将相同的组件与注入的字段一起使用
- Instance the component
- Invoke injector - IComponentInstantionListener.onInstantiation(Component component)
- Inject annotated field
- Use component (render, etc.)
- Next request(s) - use the same component with injected fields
该怎么办?
使用注入到字段中的代理类。调用代理类时,它将使用当前的bean。
What to do? Use a proxy class that is injected into field(s). When the proxy class is invoked it ever uses the current bean.
请参见
AnnotProxyFieldValueFactory,位于 http://ci.apache.org/projects/wicket/apidocs/6.0.x/org/apache/wicket/spring /injection/annot/AnnotProxyFieldValueFactory.html
即使您必须编写自己的实现或使用Wicket Contrib或Wicket Stuff。
Even you have to write your own implementation or look to Wicket Contrib or Wicket Stuff.
这篇关于Apache Wicket:在表单验证器中注入依赖项(使用Guice)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!