将bean注入helper类时遇到问题.它的工作原理基本上是这样的:我在页面构造函数中创建一个对象,它可以完成一些工作,返回一些数据并在页面上显示这些数据.在此辅助对象中,应通过@Au
这是页面:
public class Page extends BasePage {
public Page() {
HelperObject object = new HelperObject(new Application("APP_NAME"));
String result = object.getData();
add(new Label("label", result));
}
}
助手对象:
public class HelperObject {
private Application app;
@Autowired
private Service service;
public HelperObject(Application app) {
this.app = app;
}
public String getData() {
// use service, manipulate data, return a string
}
}
@SpringBean仅将依赖项注入从Wicket的Component继承的类中. @Autowired只将依赖注入Spring自己创建的类中.这意味着您无法自动将依赖项注入到使用new创建的对象中.
(编辑:您还可以通过在构造函数中注入来向您的类添加@SpringBean注入:
InjectorHolder.getInjector()注入(本);)
我的正常解决方法是使用我的应用程序类来提供帮助. (我对你使用新的Application(…)感到有些困惑.我认为这实际上不是org.apache.wicket.Application.)例如:
public class MyApplication extends AuthenticatedWebApplication implements
ApplicationContextAware {
private ApplicationContext ctx;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.ctx = applicationContext;
}
public static MyApplication get() {
return (MyApplication) WebApplication.get();
}
public static Object getSpringBean(String bean) {
return get().ctx.getBean(bean);
}
public static <T> T getSpringBean(Class<T> bean) {
return get().ctx.getBean(bean);
}
....
}
在我的Spring应用程序上下文中
<!-- Set up wicket application --> <bean id="wicketApplication" class="uk.co.humboldt.Project.MyApplication"/>
然后我的帮助对象按需查找服务:
public class HelperObject {
private Service getService() {
return MyApplication.getSpringBean(Service.class);
}
