@ApplicationScoped - 是否可以获得临时注射?

问题描述:

我想建立一个@ApplicationScoped缓存机制,它基本上只是存储一些在启动时读取的数据库值。是否有可能无需一直持有EntityManager和其他注入依赖项(即查询工厂)?初始化期间我只需要它们。@ApplicationScoped - 是否可以获得临时注射?

我不确定容器是否真的保持连接打开。但让我们说,它会。首先,您需要通过CDI注射EntityManager。你可以这样做,像这样:

@ApplicationScoped 
public class EntityManagerProducer { 
    @Produces 
    @PersistenceContext(unitName = "my-pu-name") 
    private EntityManager em; 
} 

那么你的初始化方法中,你可以使用:

public void init() { 
    EntityManager entityManager = CDI.current().select(EntityManager.class).get(); 
    // Do some stuff here 
    CDI.current().select(Entitymanager.class).destroy(entityManager); 
} 

.destroy应确保依存度活跃了。