jsf 2.0 spring 3范围请求不起作用

时间:2012-05-31 07:15:27

标签: spring jsf-2

我正在尝试使用spring为jsf提供托管bean。我假设JSF容器将选择@ManagedBean将JSF中的EL链接到托管bean,即使我通过在faces-config.xml中配置spring用法来使用spring也是如此。

Spring应该提供bean,但是现在谁管理bean的范围?

我已尝试在bean上使用注释使其成为Request范围,但它们不起作用。

@ManagedBean(name="helloBean") //meant for JSF
@RequestScoped //meant for JSF
@Scope(value="request") //meant for spring
@Controller //meant for spring
public class HelloBean implements Serializable {

实际上早些时候我使用普通的JSF和@ManagedBean并且@RequestScoped运行良好。现在,当我尝试使用spring进行集成时,示波器无效。

我甚至尝试在spring config中设置bean作用域,但它们在spring(singleton和prototype)的上下文中按预期工作,但不是web请求上下文。

我试图避免使用上面的@Scope和@Controller注释,希望JSF能够管理范围,但似乎不是。

以下是我的spring config和MyHelloBean的文件片段,它可能有助于更好地沟通。

<bean id="helloBean" class="com.mkyong.common.HelloBean" init-method="init" />

<bean id="myHelloBean" class="com.mkyong.common.MyHelloBean" init-method="init" >
        <property name="helloBean" ref="helloBean"></property>
</bean>

@ManagedBean
@RequestScoped
@Scope(value="request")
@Controller
public class MyHelloBean implements Serializable {

    private static final long serialVersionUID = 1L;
    //@ManagedProperty(value = "#{helloBean}")
    private HelloBean helloBean;

参见上面的MyHelloBean我使用spring DI来设置helloBean,它被spring设置得很好。我已经注释掉了@ManagedBean,我认为我可以把它留在那里,因为它会被Spring忽略,而且我觉得JSF不会处理它,但为了安全起见,我为JSF注释了它没有处理它。 / p>

要完成我在faces-config中使用以下来激活弹簧使用。

<el-resolver> 
org.springframework.web.jsf.el.SpringBeanFacesELResolver 
</el-resolver> 

此致

米滕。

2 个答案:

答案 0 :(得分:5)

我们的团队遇到了集成JSF和Spring bean的类似问题,包括其范围问题。在这里,我要分享我们的知识。

作用域

现在基本上,当您在应用程序上下文中定义时, Spring将管理您的bean,因此范围。 Spring会将JSF范围注释映射到其原生范围注释。

  • Spring和JSF支持提供范围时的示例:

@RequestScoped注释将映射到@Scope(“request”)Spring的注释等,以及其他受支持的范围。

  • 当Spring不支持JSF提供的范围时的示例:

@ViewScoped未在Spring的本机范围注释中定义,因此(不确定)它将使用Spring的默认范围,即单例或请求范围(不确定)。

Bean Injection

在JSF2中,您使用@ManagedProperty注释进行注入,而Spring使用@Autowired注释。 有什么区别和选择?

  • 使用@ManagedProperty注入Spring bean:

要注入的Spring组件必须具有与jsf注入注释的值匹配的值:@Component(value =“valueMatches”)注入@ManagedProperty(value =“valueMatches”)。

  • 使用@Autowired注入Spring bean:

要注入的Spring组件必须不需要自定义值来区分,如果它是您注入的bean的唯一实现:@Component注入@Autowired。

我们的方式

我们使用Spring的注释来定义Beans,Scopes和Injection。

我们用@Scope(value =“desiredScope”),@ Controller(value =“beanName”)和@Qualifier(value =“beanName”)注释标记了JSF bean。稍后可以通过@Controller注释中定义的“beanName”值在faces-config.xml的帮助下从JSF上下文访问。

我们使用@Service注释标记了Spring服务。

我们使用@Autowired注释注入了Spring服务和JSF bean。

我们在网上找到了ViewScope和FlashScope自定义实现,并将它们用于我们的bean。因此,我们没有丢失任何JSF2范围,甚至添加了新的范围。

希望这有帮助。

答案 1 :(得分:2)

您的方法有点令人困惑,因为您似乎正在混合Spring XML配置和Spring Annotation-based配置。如示例here所述,如果您使用带注释的配置,那么您应该:

<context:component-scan base-package="com.yourcom.package" />

命令Spring扫描注释。否则,如果您正在使用XML配置,那么您应该:

<bean id="helloBean" class="com.mkyong.common.HelloBean" init-method="init" scope="request" />

默认情况下,Spring bean的scopesingleton