如何集成Spring和JSF?我按照Spring文档(这个主题很少)进行了google搜索,目前我发现了两种工作方式:
JSF Managed Bean将是Spring @Component / @Named(但似乎没有工作JSF范围,只有Spring范围):
@Component
@Scope("request")
public class ItemController {
@Autowired
private ItemService itemService;
}
我将使用@ManagedBean,JSF作用域工作,但我无法使用@Autowired自动装配Spring bean,bean必须包含setter,我不确定这是否是最佳做法:
@ManagedBean
@RequestScoped
public class ItemController {
@ManagedProperty("#{itemService}")
private ItemService itemService;
public void setItemService(ItemService itemService) {
this.itemService = itemService;
}
}
还有别的吗?
答案 0 :(得分:2)
我肯定会选择1号方式(并且在相当多的项目中也是如此)。将JSF托管bean与Spring bean混合起来没有任何意义,除非你有充分的理由这样做。使用Spring托管bean,您有更多的可能性,即使对于托管bean,您也可以使用Spring的全部功能。
理论上,还有第三种方法:您可以将CDI用于UI层,将Spring用于后台。如果您不想使用完整的Java EE环境但仍希望从UI层中的CDI和Myfaces CODI / Deltaspike中受益,那么这可能是一个选项。但在这种情况下,您还需要一个CDI设置和一个CDI到Spring桥。
答案 1 :(得分:1)
我有一段时间没有同样的问题。
虽然还有弹簧EL增强功能可以在那里查找弹簧豆,但我仍然发现JSF和弹簧之间的差异太大,无法以无缝方式交叉。
因此,我的建议是明确差距而不是试图跨越它。
在我的情况下,我最终得到了一个服务定位器模式,可以访问spring上下文并在那里查找..
@ManagedBean
@ApplicationScoped
public class ServiceLocator {
public <T> T getServiceByType(Class<T> serviceType) {
getSpringContext().getBean(serviceType);
}
public ApplicationContext getSpringContext() {
return FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
}
}
@ManagedBean
@ViewScoped
public class ViewBean {
@ManagedProperty("#{serviceLocator}")
protected ServiceLocator serviceLocator;
public void actionMethod() {
serviceLocator.getService(BookingService.class).book(roomId, fromDate, toDate);
}
}
从记忆中写出,但你可能会得到要点
答案 2 :(得分:1)
您可以使用JSF-Spring集成项目中的@AutowiredBean将JSF托管bean注入Spring bean:
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class JsfTest implements Serializable {
private static final long serialVersionUID = 1L;
@AutowiredBean
private JsfBean jsfBean;
...
}
将Maven artifact com.intersult:jsf-spring:2.2.0.1-SNAPSHOT添加到您的项目中,请参阅https://www.intersult.com/wiki/page/JSF%20Spring%20Integration(使用翻译按钮)。
答案 3 :(得分:0)
一种方法是让Spring管理你的所有bean,你肯定需要在faces-config.xml中使用SpringBeanFacesELResolver
Bean:
@Component
@Scope("view")
public class UserBean
faces-config.xml:
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
Spring提供了添加自定义范围的选项,需要实现org.springframework.beans.factory.config.Scope接口。使用applicationcontext.xml注册Spring。
applicationcontext.xml在自定义视图&#39;范围实施: [ViewScope是我对Scope接口的实现]
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="com.org.common.ViewScope"/>
</entry>
</map>
</property>
</bean>