单例会话 Bean

Singleton Session Bean

我正在尝试为单个会话 bean 创建一个基本模板。然后,我把例子包含在 "The Architecture of the counter":

https://docs.oracle.com/javaee/7/tutorial/ejb-basicexamples002.htm

但是,当 运行 示例时,我无法打印 count.hitCount 的值。

我发现访问变量时的常见问题是没有 getter。例如,在 index.html:

<ui:define name="title">
        This page has been accessed #{count.hitCount} time(s).
</ui:define>

但是,在 Count.java 中包括 getter getHitCount():

@Named
@SessionScoped
public class Count implements Serializable {

    @EJB
    private CounterBean counterBean;

    private int hitCount;

    public Count() {
        this.hitCount = 0;
    }

    public int getHitCount() {
        hitCount = counterBean.getHits();
        return hitCount;
    }
    public void setHitCount(int newHits) {
        this.hitCount = newHits;
    }

最后,CounterBean.java增加变量:

@Singleton
public class CounterBean {
    private int hits = 1;

    // Increment and return the number of hits
    public int getHits() {
        return hits++;
    }
}

非常感谢您的帮助和评论。

带有显示次数计数器的 facelet:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
  <h:head>
    <title>Facelet Title</title>
</h:head>
  <h:body>
    This page displayed #{counterController.hitCount} times.
  </h:body>
</html>

CounterController 是一个 @RequestScoped bean,用于在其 @PostConstruct 方法中递增 CounterBean.hitCount

package x;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@Named( value = "counterController" )
@RequestScoped
public class counterController
{

  @EJB
  private CounterBean counterBean;

  @PostConstruct
  public void initialize()
  {
    counterBean.incHitCount();  
  }

  public int getHitCount()
  {
    return counterBean.getHitCount();
  }

  public CounterController()
  {
  }

}

CounterBean 是一个 @Singleton EJB 来存储 hitCount。 @StartUp 注释做一个急切构造的 bean(在应用程序启动时创建,在接受任何客户端请求之前):

package x;

import javax.ejb.Singleton;
import javax.ejb.Startup;
import lombok.Data;

@Singleton
@Startup
public class CounterBean
{
  private int hitCount;

  public int getHitCount()
  {
    return hitCount;
  }

  public void incHitCount()
  {
    hitCount++;
  }

  public CounterBean()
  {}
}