【问题标题】:CDI Inject EntityManagers by field name with @ProducesCDI 使用 @Produces 按字段名称注入 EntityManager
【发布时间】:2023-03-24 21:21:01
【问题描述】:

我正在实现一个部署到 Wildfly 8.2.0 的 Java EE 应用程序。有多个 EntityManager,我想按字段名称注入。为此,我使用 @Produces 创建了一个生产者方法,该方法从 InjectionPoint 获取字段名称。

public class Resources {

    @PersistenceContext(unitName = "primary")
    private EntityManager primaryEm;

    @PersistenceContext(unitName = "secondary")
    private EntityManager secondaryEm;

    @Produces
    public EntityManager getEntityManager(InjectionPoint injectionPoint)
        throws Exception {
        Field field = getClass().getDeclaredField(
               injectionPoint.getMember().getName());

        return (EntityManager) field.get(this);
    }
}

然后我可以简单地使用正确的字段名称注入 EntityManager:

@Inject
private EntityManager primaryEm;

到目前为止,此解决方案有效,但 CDI 中是否有另一种更优雅的方式来实现此“按字段名称注入”功能?

【问题讨论】:

    标签: java ejb cdi entitymanager


    【解决方案1】:

    我认为您的解决方案是最漂亮的。或者,也许您可​​以详细描述它对您的优雅意味着什么?

    【讨论】:

    • 我很高兴读到。好吧,我想知道如果没有包括反射在内的生产者方法,是否有可能解决这个问题。
    猜你喜欢
    • 2016-06-07
    • 2020-05-15
    • 1970-01-01
    • 2019-06-15
    • 2011-11-26
    • 1970-01-01
    • 2014-11-10
    • 2016-01-03
    • 2017-03-21
    相关资源
    最近更新 更多