EJB和静态字段 [英] EJB and static fields

查看:56
本文介绍了EJB和静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在无状态会话bean中有一个静态的只读集合.理想情况下,只要应用程序正在运行,它将仅初始化一次,并且可用于Bean实例.

I would like to have a static read only collection in a stateless session bean. Ideally it will only be initialized once and available to bean instances as long as the application is running.

让我们假设此应用程序部署在具有多个服务器/JVM的集群环境中.

Let's assume that this application is deployed in a clustered environment with multiple servers/JVMs.

据我了解,在第一种情况下,静态变量barList在容器创建bean的同时被初始化,并且生存时间与bean一样长(甚至更长),并且没有任何危险.在bean实例还活着的时候被垃圾回收了.

As I understand it, in the first case, the static variable barList gets initialized at the same time when the bean is created by the container and lives as long as the bean (or maybe even longer?) and there's no danger of it being garbage collected while the bean instance is alive.

在第二种情况下,当Foo类被加载时(即执行bean的getBarList()方法时),barList被初始化.但是,返回时会发生什么呢?Bean方法执行完后会销毁它吗?

In the second case, barList gets initialized when the Foo class gets loaded which is when the bean's getBarList() method gets executed. What happens when it's returned though? Will it be destroyed after the bean method is done executing?

情况1:

@Stateless
public class MrBean implements BeanInterface{

private static final List<Bar> barList;

static{

barList = new ArrayList<Bar>();

//create some bars, add them to the list

}

public List<Bar> getBarList(){

    return barList;
}
}

情况2:

@Stateless
public class MrBean implements BeanInterface{

public List<Bar> getBarList (){

return Foo.barList;

}

}

public class Foo {

public static final List<Bar> barList;

static{ 

barList = new ArrayList<Bar>();

// create bars, add them to barList 

}

}

推荐答案

我宁愿创建一个 @Singleton bean,并让它管理和提供该列表.然后,您将具有以下优点:

I would rather create a @Singleton bean and let it manage and serves the list. Then you have the following advantages:

  1. 列表对于整个应用程序仅初始化一次,并且不必为 static 静态,因此您符合EJB标准.
  2. 可以通过应用程序启动而不是通过 @Startup @PostConstruct 批注来初始化EJB和列表.
  3. 可以使用 @Lock(READ) @Lock(WRITE)同时访问/操作该列表.
  4. 您可以在一种EJB方法中使用@Observes模式来响应事件并在需要时重新加载列表
  1. the list is initialized only once for the whole application and doesn't have to be static, so you are compliant with EJB standard.
  2. the EJB and the list can be initialized at application startup rather than EJB initialization by means of @Startup and @PostConstruct annotations.
  3. the list can be accessed/manipulated concurrently by using @Lock(READ) @Lock(WRITE).
  4. you can use @Observes pattern in one of your EJB method to react to event and reload the list if needed

这篇关于EJB和静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆