JSF 2注入了带有@ManagedProperty且没有xml的Springbean/service



我想使用jsf注释和一些spring将springbean/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,这样的事情可能发生吗。例如我不想使用类似的东西

FacesContextUtils.getWebApplicationContext(context).getBean("MySpringBean");

或在faces-config.xml

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>com.mytest.MyBean</managed-bean-class>
    <managed-bean-scope>view</managed-bean-scope>
    <managed-property>
        <property-name>mySpringBean</property-name>
        <value>#{mySpringBean}</value>
    </managed-property>
</managed-bean>

有注释和没有注释的情况下,上面的内容可能吗定义的所有jsf-beans/properties和springbeans/properties配置xml文件中的每个bean?

如果您已经有了Spring容器,为什么不使用它的@Autowired注释呢。为此,请按照Boni的建议更新您的faces-config.xml。然后在这个之后将这些监听器添加到你的web.xml中

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

然后将这些添加到applicationContext.xml 中

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

现在您可以使用Spring注释,您的bean将是这样的:

package com.examples;
@Component
@Scope(value="request")
public class MyBean {
    @Autowired
    private MySpringBeanClass mySpringBean;
}

使用@Service 为您的MySpringBeanClass添加注释

另请参阅:

  • @范围("请求")不起作用

将此代码放入您的faces-config.xml 中

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>
</faces-config>

然后在您的ManageBean构造函数调用中;

WebApplicationContext ctx =  FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
mySpringBean = ctx.getBean(MySpringBean.class);

MySpringBean是指您的SpringBean类

假设您已在web.xml和applicationContext.xml中正确配置了Spring。在faces-config.xml 中创建以下条目

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

上面给出的示例代码看起来不错。上面的条目将首先在JSF管理的bean中查找托管属性,如果找不到,则在Spring管理的beans中搜索。您的springbean应该标记了适当的注释,并且@ManagedProperty中给定的名称应该与给定给bean的default/name匹配。

正如@Boni所提到的,这是不需要的,它是自动注入的。我使用了你想要的设置。

附带说明:由于您选择了视图范围,请查看此链接@ViewScoped 的优点和缺点

最新更新