【问题标题】:JSF inject backing bean into SingletonJSF 将 backing bean 注入 Singleton
【发布时间】:2014-08-11 03:36:57
【问题描述】:

我正在尝试将 JSF 视图呈现为字符串。我有一个 Singleton、一个支持 bean 和一个类似于以下示例的视图。

我不知道如何将我的支持 bean 注入我的单例中。 使用下面的代码,控制台中会打印日志行“Fine: TestBean created手动”,这意味着 bean 没有正确实例化。我还收到以下警告:

严重:无法在实例 javax.faces.ViewRoot 上调用 @PostConstruct 注释方法

还有一个异常堆栈:

com.sun.faces.spi.InjectionProviderException: com.sun.enterprise.container.common.spi.util.InjectionException: Wrong invocation type
    at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:231)
[...]
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Wrong invocation type
at org.glassfish.faces.integration.GlassFishInjectionProvider.getNamingEnvironment(GlassFishInjectionProvider.java:262)
at org.glassfish.faces.integration.GlassFishInjectionProvider.invokePostConstruct(GlassFishInjectionProvider.java:229)

代码的目的是呈现个性化的邮件。我正在尝试将一些值放在支持 bean 中,然后将视图呈现为字符串作为邮件正文。 我尝试了支持 bean 的各种范围。

谢谢,

查理

test.xhtml:

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:c="http://java.sun.com/jsp/jstl/core">

    <h:body>
        <h1> Hello </h1>
        <p>
            Bean String : #{testBean.theString}
        </p>
        <h:form>
            <h:commandLink value="Render it"
                           action="#{testBean.actionRenderTest()}"/>
        </h:form>
    </h:body>
</html>

TestBean.java:

// skipped package and imports

@ManagedBean
@ApplicationScoped
public class TestBean implements Serializable{

    @EJB
    private TestSingleton singleton;

    private String theString;

    public String getTheString() {
        return theString;
    }

    public void setTheString(String theString) {
        this.theString = theString;
    }

    public void actionRenderTest() {
        singleton.renderTest();
    }

}

TestSingleton.java:

// package&imports

@Singleton
@Startup
public class TestSingleton implements Serializable {

    @ManagedProperty("#{testBean}")
    private TestBean testBean;


    public void renderTest() {
        if (testBean == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            testBean = context.getApplication().evaluateExpressionGet(context, "#{testBean}", TestBean.class);
            Logger.getLogger(TestSingleton.class.getName()).fine("TestBean created manually");
        }

        testBean.setTheString("string set from my singleton");
        try {
            FacesContext context = FacesContext.getCurrentInstance();
// store the original response writer
            ResponseWriter originalWriter = context.getResponseWriter();

// put in a StringWriter to capture the output
            StringWriter stringWriter = new StringWriter();
            ResponseWriter writer = createResponseWriter(context, stringWriter);
            context.setResponseWriter(writer);

// create a UIViewRoot instance
            ViewHandler viewHandler = context.getApplication().getViewHandler();
            final String template = "/test/test.xhtml";
            UIViewRoot view = viewHandler.createView(context, template);

// the fun part -- do the actual rendering here
            ViewDeclarationLanguage vdl = viewHandler
                    .getViewDeclarationLanguage(context, template);
            vdl.buildView(context, view);
            renderChildren(context, view);

// restore the response writer
            if (originalWriter != null) {
                context.setResponseWriter(originalWriter);
            }

            Logger.getLogger(TestSingleton.class.getName()).log(Level.FINE, stringWriter.toString());
        } catch (IOException ex) {
            Logger.getLogger(TestSingleton.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Create ResponseWriter. Taken from FaceletViewDeclarationLanguage.java of
     * MyFaces.
     */
    private ResponseWriter createResponseWriter(FacesContext context,
            Writer writer) {
        ExternalContext extContext = context.getExternalContext();
        Map<String, Object> requestMap = extContext.getRequestMap();
        String contentType = (String) requestMap.get("facelets.ContentType");
        String encoding = (String) requestMap.get("facelets.Encoding");
        RenderKit renderKit = context.getRenderKit();
        return renderKit.createResponseWriter(writer, contentType, encoding);
    }

    /**
     * Render a UIComponent. Taken from JSF.java of Seam 2.2.
     */
    private void renderChildren(FacesContext context, UIComponent component)
            throws IOException {
        List<UIComponent> children = component.getChildren();
        for (int i = 0, size = component.getChildCount(); i < size; i++) {
            UIComponent child = (UIComponent) children.get(i);
            renderChild(context, child);
        }
    }

    /**
     * Render the child and all its children components.
     */
    private void renderChild(FacesContext context, UIComponent child)
            throws IOException {
        if (child.isRendered()) {
            child.encodeAll(context);
        }
    }
}

【问题讨论】:

    标签: java jsf jsf-2


    【解决方案1】:

    我认为这是因为你有循环依赖。 TestBean 参考TestSingletonTestSingleton 要求注入TestBean

    【讨论】:

    • 双向注入完全有效。
    【解决方案2】:

    @ManagedProperty 注解在@ManagedBean 之外无效。

    来自http://docs.oracle.com/javaee/6/api/javax/faces/bean/ManagedProperty.html

    如果这个注解出现在一个类上 没有 ManagedBean 注解,实现必须 对此注释不采取任何操作

    使用@Inject 和@ApplicationScoped 注释你的bean

    import javax.inject.Named;
    import javax.enterprise.context.ApplicationScoped;
    
    @Named
    @ApplicationScoped
    public class TestBean implements Serializable
    

    并在你的@Singleton 中添加@Inject 注解

    @Singleton
    @Startup
    public class TestSingleton implements Serializable {
    
        @Inject
        private TestBean testBean;
    

    【讨论】:

    • 我猜你的意思是 @Named 在支持 bean 上
    • 这没有效果。调用单例方法时,testBean 变量仍然为空,我得到同样的错误信息和异常。
    • 请验证所有导入是否正确,@ApplicationScoped 来自 javax.enterprise.context.ApplicationScoped 。这在我们的项目中有效。是否有任何警告或错误?
    • 还要确保启用了 CDI(WEB-INF 中有 beans.xml)
    • 对不起。干净的重新部署后,bean 被正确注入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2013-06-25
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2023-03-27
    • 2015-01-13
    相关资源
    最近更新 更多