JSF 2使用@ManagedProperty注入Spring bean / service而没有xml
我想使用jsf注释和一些spring注释将spring bean / service注入jsf托管bean。 (在jsf bean上我只想使用jsf注释)我不想使用像@named
/ @inject
这样的注释。
我试图在网上找到一个解决方案,但没有任何运气。
例
@ManagedBean @ViewScoped public class MyBean { @ManagedProperty(value = "#{mySpringBean}") private MySpringBean mySpringBean; public void setMySpringBean(MySpringBean mySpringBean) { this.mySpringBean = mySpringBean; } public void doSomething() { //do something with mySpringBean } }
没有使用xml就可以实现这样的function。 例如,我不想使用类似的东西
FacesContextUtils.getWebApplicationContext(context).getBean("MySpringBean");
或者在faces-config.xml
myBean com.mytest.MyBean view mySpringBean #{mySpringBean}
类似于上面的注释,并没有定义所有jsf bean /属性和config xml文件中每个bean的spring beans /属性?
如果您已经拥有Spring容器,为什么不使用它的@Autowired注释。 为此,按照Boni的建议更新faces-config.xml。 然后在这之后将这些侦听器添加到web.xml
contextConfigLocation /WEB-INF/applicationContext.xml org.springframework.web.context.ContextLoaderListener org.springframework.web.context.request.RequestContextListener
然后将这些添加到applicationContext.xml中
现在你可以使用Spring注释,你的bean将是这样的:
package com.examples; @Component @Scope(value="request") public class MyBean { @Autowired private MySpringBeanClass mySpringBean; }
使用@Service注释MySpringBeanClass
也可以看看:
- @Scope(“请求”)无效
将此代码放在faces-config.xml中
org.springframework.web.jsf.el.SpringBeanFacesELResolver
然后在ManageBean Constructor中调用;
WebApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); mySpringBean = ctx.getBean(MySpringBean.class);
MySpringBean意味着你的Spring Bean类
假设您已在web.xml和applicationContext.xml中正确配置了Spring。 在faces-config.xml中进行以下输入
org.springframework.web.jsf.el.SpringBeanFacesELResolver
上面给出的示例代码似乎很好。 如果找不到将在Spring管理的bean中搜索,那么上面的条目会发生什么,Managed Property将首先在JSF管理的bean中查找。 您的spring bean应该标记正确的注释,并且@ManagedProperty中给出的名称应该与给予bean的默认/名称匹配。
如@Boni所述,不需要它是自动注入的。 我根据你的需要使用了设置。
附注:由于您选择查看范围,请查看此链接@ViewScoped的好处和陷阱