CDI 1.1 使用后立即处理注入的资源

CDI 1.1 Dispose injected resource Immediate after using

我有一个简单资源class

@Vetoed
public class SimpleResource {
  private String value="TestValue";
  public void open(){
     System.out.println("Open SR method");  
 }  
 public void close(){
   System.out.println("Close SR method");
 }
 public String getValue() {
   return value;
 }  
}

然后我创建了一个 Producer Class

@Singleton
public class EntityManagerProducer {

 @Produces
 @Default
 @Dependent
 public static SimpleResource createSimpleResource() {
   SimpleResource sr = new SimpleResource();
   System.out.println("Open SR");
   sr.open();
   return sr;
 }

 public static void disposeSimpleResource(@Disposes @Default SimpleResource  simpleResource) {
  System.out.println("Close SR");
  simpleResource.close();
  }
}

比单例业务要好class

@Default
@Singleton
public class InjectConstructor {
 private  String value="init";

 @Inject
 public InjectConstructor(SimpleResource sr){
  value=sr.getValue();
 }

 public String getValue() {
   return value;
 }
}

测试方法运行

 @Test
 public void injectConstructor(){
  Weld weld = new Weld();
  WeldContainer container = weld.initialize();
  InjectConstructor inst= container.select(InjectConstructor.class).get();   
  System.out.println("Value= "+inst.getValue());
 }

在 运行nning 测试程序后,我得到了这样的响应:

INFO org.jboss.weld.Bootstrap - WELD-ENV-002003:Weld SE 容器 STATIC_INSTANCE 已初始化
打开 SR
打开SR方法
值=测试值
关闭容器
关闭 SR
关闭SR方法

问题是 "SimpleResource" 在构造函数 @Inject 之前打开,但在构造函数退出后没有关闭。

问题是如何通过构造函数注入注入"SimpleResource"并在构造函数退出后立即关闭?

唯一的方法是使用@Observes 方法吗?

public void watchStartup(@Observes @Initialized(ApplicationScoped.class) Object ctxEvent, SimpleResource sr) {
 ...
}

因为您要使 SimpleResource 依赖,所以它的范围与父级的生命周期相关联,因此它像单例一样进行管理。要执行您正在寻找的操作,您必须让构造函数直接知道该 bean,并且可能使用 Unmanaged 创建然后销毁一个实例。

Martin Couba 帮我解决了这个问题。

you could make use of @javax.enterprise.inject.TransientReference. The producer method for SimpleResource is @Dependent so the disposer method should be called when the invocation of the constructor completes.

@Inject
public InjectConstructor(@TransientReference SimpleResource sr) {
  value = sr.getValue();
}

非常感谢。这是非常优雅的解决方案