0

这是一个菜鸟问题,对不起。

我开发了一个 jsf-2 应用程序(在 Tomcat 上),它在会话范围内声明了一个大控制器 bean。

现在,我犯的错误是将所有会话范围的变量作为静态变量放在这个 bean 中,认为它们不会在应用程序的不同实例之间共享。但它们是——静态变量在同一个 JVM 上的所有应用程序实例之间共享,这实际上是有道理的。无论如何,我所有的代码目前都是这样的:

@SessionScoped
@ManagedBean
public ControllerBean{
static private String aString = "session wide value for a string";
//static getter and setter for astring

}

@viewscoped
@ManagedBean
public class OneRandomViewScopedBean{
String oneString = ControllerBean.getAString();
//operations on this string...
ControllerBean.setAString(newValueForString);
} 

我能否获得有关如何重构代码以删除 ControllerBean 中的静态变量的指针?我想解决方案很简单,但我现在看不到。

注意:我不需要持久化数据,因为数据量很小,并且在应用程序关闭后它们可能会消失

谢谢!

4

1 回答 1

6

删除static修饰符(这确实是一个巨大的错误;这个问题不是 JSF 特有的,而只是基本的 Java。在继续 JSF 之前,我真的会花更多的时间来学习基本的 Java)并用于@ManagedProperty注入其他 bean 或其属性。

@ManagedBean
@SessionScoped
public class ControllerBean {

    private String aString = "session wide value for a string";
    // Non-static getter and setter for aString.

    // ...
}

@ManagedBean
@ViewScoped
public class OneRandomViewScopedBean {

    @ManagedProperty("#{controllerBean}")
    private ControllerBean controllerBean;
    // Setter for controllerBean. Getter is not mandatory.

    public void someAction() {
        controllerBean.setAString(newValueForString);
    }

    // ...
} 

也可以看看:

于 2012-11-14T13:12:55.110 回答