使用生成器创建应用程序范围的类成员 [英] Creating application scoped class member with a producer
问题描述
是否可以说,在下面的代码中,Hazelcast实例将是应用程序作用域?
Is it true to say that in the code bellow, the Hazelcast instance will be application scoped ?
@ApplicationScoped
public class Producer {
private HazelcastInstance instance;
@PostConstruct
public void afterCreate() {
instance = Hazelcast.newHazelcastInstance();
}
@Produces
public HazelcastInstance getInstance() {
return instance;
}
}
编辑
此解决方案:
- 确保生成的是应用程序作用域。
- 提供优雅的Hazelcast关闭。
@ApplicationScoped
public class Producer {
private HazelcastInstance instance;
private Producer() {}
@PostConstruct
public void afterCreate() {
instance = Hazelcast.newHazelcastInstance();
}
@PreDestroy
public void beforeDestroy() {
if(instance != null) {
instance.shutdown();
}
}
@Produces
@ApplicationScoped
public HazelcastInstance getInstance() {
return instance;
}
}
推荐答案
你生产者
bean将是应用程序作用域,这一点很清楚。
但是, HazelnutInstance
bean将是 @Dependent
。
You Producer
bean will be application scoped, that much is clear.
However, HazelnutInstance
bean will be @Dependent
.
因此,如果您在代码中的某处执行 @Inject HazelnutInstance
,它将从CDI视点注入一个依赖实例。
Therefore, if you, somewhere in your code, do @Inject HazelnutInstance
it will inject a dependent instance from CDI viewpoint.
但是你总是返回相同的实例,从不在生产者中创建新对象,所以理论上,你正在共享那个实例。
But you always return the same instance, never create new object in your producer, so theoretically, you are sharing that one instance.
然而,请留意豆生命周期! @Dependent
当它们被注入的bean被销毁时,它们将被销毁。所以现在假设这样的破坏尝试 - Weld将尝试销毁你的依赖bean并将调用 @PreDestroy
(在经典bean上)或 @Disposes
(在带有生产者的bean上)方法。
However, look out for bean lifecycles! @Dependent
beans will be destroyed when the bean where they were injected is destroyed. So now assume it comes to such destruction attempt - Weld will try to destroy your dependent bean and will call @PreDestroy
(on "classic" beans) or @Disposes
(on beans with producers) method on it.
因此,在你的情况下,如果有一个处理器方法某处,处理 HazelcastInstance
,这可能会导致麻烦,因为每次Weld试图销毁/处置该依赖bean时都会调用它。
Therefore, in your case, if there is a disposer method somewhere, which handles HazelcastInstance
, that might cause a trouble as it would be invoked every time Weld attempts to destroy/dispose of that dependent bean.
IMO你会好过的话你制作 HazelcastInstance
应用范围。例如,
IMO you would be better off if you make HazelcastInstance
application scoped. E.g.
@Produces
@ApplicationScoped
public HazelcastInstance getInstance() {
return instance;
}
这篇关于使用生成器创建应用程序范围的类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!