如何使用Spring服务在JSF管理的bean?(How to use Spring service

2019-07-04 00:42发布

JSF是非常流行的技术在Java世界,然而,随着春季的合作仍然是不好受,需要“讨厌”黑客。 我现在有这个“黑客”的一个问题。

Spring服务所使用的注射SpringBeanFacesELResolver 。 它被配置在faces-config.xml

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

春季服务注入是非常难看,但它的工作:

@ManagedProperty(value="#{customerService}")
CustomerService customerService;

但也有问题。 JSF从我的要求托管bean应该是可序列化。 这意味着,春节服务也必须是可序列化,或现场应该是短暂的。 当磁场是短暂的,注射不工作(我有空在这一领域)。 并使得Spring服务序列化是在我看来不是一个好主意,一个潜在的性能问题 - 应该与Hibernate情况下,数据源发生什么,而这一切都注入春天的服务?

那么,什么是使用Spring服务withing JSF管理bean的正确的和少不好受呀?

Answer 1:

我经历了很多与org.springframework.web.jsf.el.SpringBeanFacesELResolver问题了。 大多与不匹配的对象范围(Spring有没有相当于JSF的看法范围和谈话的范围)。 有些人还抱怨系列化问题。

我成功地应用在这篇文章中提出的解决方案: http://www.beyondjava.net/blog/integrate-jsf-2-spring-3-nicely/ 。

就我而言,系列化,是不是一个问题,我只关心Bean的作用。 我希望JSF而不与Spring bean的生命周期的干扰完全管理的支持豆生命周期。

我做了JSF管理的bean加载Spring上下文和自动装配自己从JSF上下文的访问Spring管理的bean。

我制定了以下JSF bean的超类:

public abstract class AutowireableManagedBean {

    protected AutowireCapableBeanFactory ctx;

    @PostConstruct
    protected void init() {
        logger.debug("init");
        ctx = WebApplicationContextUtils
                .getWebApplicationContext(
                        (ServletContext) FacesContext.getCurrentInstance()
                                .getExternalContext().getContext())
                .getAutowireCapableBeanFactory();
        // The following line does the magic
        ctx.autowireBean(this);
    }
   ...
}

然后,我的具体JSF支持Bean这个样子(我能使用的视图范围内没有问题):

@ManagedBean
@ViewScoped
public class MyBackingBean extends AutowireableManagedBean {

    @Autowired
    private MyDao myDao;


文章来源: How to use Spring services in JSF-managed beans?