Tomcat 7、JSF 2.0 和 @PostConstruct

Posted

技术标签:

【中文标题】Tomcat 7、JSF 2.0 和 @PostConstruct【英文标题】:Tomcat 7, JSF 2.0 and @PostConstruct 【发布时间】:2011-07-14 04:56:42 【问题描述】:

我不知道我做错了什么,请帮助:

    /lib 文件夹中没有额外 jar 的全新 Tomcat 7 在 WEB-INF/lib(jsf-api.jar、jsf-impl.jar)中带有 mojarra 2.0.3 库的简单网络应用 除了我的 bean 中的 @PostConstruct 外,其他都可以正常工作 - 它们根本没有被调用

日志:

Mar 12, 2011 11:19:54 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive test_web_app.war
Mar 12, 2011 11:19:54 PM com.sun.faces.config.ConfigureListener contextInitialized
INFO: Initializing Mojarra 2.0.3 (FCS b03) for context '/test_web_app'
Mar 12, 2011 11:19:54 PM com.sun.faces.spi.InjectionProviderFactory createInstance
INFO: JSF1048: PostConstruct/PreDestroy annotations present.  ManagedBeans methods marked with these annotations will have said annotations processed.

web.xml

<web-app 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-app_3_0.xsd"
           version="3.0">

  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>

</web-app>

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">
</faces-config>

方法不可达的Bean:

@ManagedBean
@ApplicationScoped
public class AppBean 

  @PostConstruct
  public void test() 
    throw new RuntimeException("test");
  

就是这样。有什么想法吗?

【问题讨论】:

整个堆栈跟踪会有所帮助。通过一些快速的谷歌搜索,我怀疑这不是问题。 @Brian Roach,实际上整个堆栈是 'Mar 12, 2011 11:19:54 PM com.sun.faces.config.ConfigureListener contextInitialized INFO: Initializing Mojarra 2.0.3 (FCS b03) for context '/test_web_app' ' 在我提到的那一行之前 【参考方案1】:

如果您的应用程序范围的托管 bean 没有在任何页面上使用,您必须使用注释

@ManagedBean(eager=true)

为了让它在启动时初始化。

【讨论】:

【参考方案2】:

@PostConstruct 如果加载了beans应该可以工作,你可以在直接调用或使用eager=true时加载它,或者在构造函数中进行初始化。

【讨论】:

以上是关于Tomcat 7、JSF 2.0 和 @PostConstruct的主要内容,如果未能解决你的问题,请参考以下文章

带有 Eclipse 和 Tomcat 的 JSF 2.0 教程 [关闭]

如何在 Tomcat 中通过 JNDI 配置 JSF 2.0 应用程序的项目阶段

@Named + @RequestScoped 在 JSF 2.0 和 JBoss 7.1.1 中不起作用

在 Servlet 2.4 容器上运行 JSF 2.0

JSF 2.0 能否与 Websphere 应用服务器版本 7.x 一起使用

从Tomcat 7迁移到8时的jsf实现版本NullPointerException