2016-07-10 62 views
1

我使用带有JSF 2.2的Spring引导。我的问题是,我可以从javax.annotation.ManagedBean创建@ManagedBean,当我运行该应用程序时,它在我的index.xhtml中工作,但是当我想要使用javax.faces.bean.ManagedBean时,不显示该值。这两者有什么区别?为什么我不能使用javax.faces.bean.ManagedBean? (我没有web.xml文件,全部在类中配置)将JSF托管bean注释与Spring Boot集成

回答

4

javax.annotation.*注释旨在从传统的JSF注释转移到CDI方法。 Spring Framework有能力读取一些CDI注释,所以这可能是此注释“有效”的原因。但是,CDI的趋势是总体使用@Named

在Spring Boot应用程序中,Spring是一个扫描注释的人,而不是JSF。因此,即使您认为该应用程序可以与@ManagedBean配合使用,您也会发现@*Scoped注释是无用的,因为所有创建的bean都是单例,这是Spring的默认范围。

最后,我做的选择是使用vanilla Spring注释和范围。由于Spring缺少JSF视图范围,因此也需要使用custom scope来模拟它。

MyBean.java:

@Component 
@Scope("view") 
public class MyBean { 
    //Here it goes your logic 
} 

ViewScope.java:

public class ViewScope implements Scope { 

    @Override 
    public Object get(String name, ObjectFactory<?> objectFactory) { 
     Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap(); 
     if (viewMap.containsKey(name)) { 
      return viewMap.get(name); 
     } else { 
      Object object = objectFactory.getObject(); 
      viewMap.put(name, object); 

      return object; 
     } 
    } 

    @Override 
    public String getConversationId() { 
     return null; 
    } 

    @Override 
    public void registerDestructionCallback(String arg0, Runnable arg1) { 

    } 

    @Override 
    public Object remove(String name) { 
     return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name); 
    } 

    @Override 
    public Object resolveContextualObject(String arg0) { 
     return null; 
    } 

} 

CustomScopeConfigurer注册视图范围:

@Bean 
public static CustomScopeConfigurer viewScope() { 
    CustomScopeConfigurer configurer = new CustomScopeConfigurer(); 
    configurer.setScopes(
      new ImmutableMap.Builder<String, Object>().put("view", new ViewScope()).build()); 
    return configurer; 
} 

最后,不要忘了加春EL解析器在faces-config.xml中做出的Spring bean可通过EL表达式:

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

参见: