java - 在不使用@Inject/@EJB的情况下从@Entity访问@Singleton

标签 java ejb domain-driven-design

我正在使用领域驱动设计(我认为!)并且我需要访问一些全局属性。我有我的@Singleton:

@Singleton
public class MyProperties {
    private Properties props;

    @PostConstruct
    private void initialize()
    {
        try {
            props.load(new FileInputStream("my.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String getProperty(String propertyName)
    {
        return props.getProperty(propertyName);
    }
}

我想这样做:

@Entity(name="MYENTITY")
public class MyEntity {
    @Inject private MyProperties props;
    void doSomething()
    {
        String myProp = props.getProperty("my-prop");
        // ...etc...
    }
}

但是,这不起作用 - propsnull,无论如何网站告诉我 not to do that ,我应该use a Service Locator instead ,但这一切都带有使用 JNDI 查找的味道 EJB 3.x kills off .

我的计划可能是尝试这种事情:

@WebListener
public class MyServletContextListener implements ServletContextListener{
    @Inject private MyProperties props;
    private MyServletContextListener theInstance;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        theInstance = this;
    }

    static public MyServletContextListener theInstance() { return theInstance; }
    public MyProperties getProperties() { return props; }
}

这有意义吗,还是我找错了树,或者我的代码中有一些愚蠢的错误?

编辑:请注意,我使用的是带有 CDI、JPA 等的普通 Java EE,没有 Spring。

EDIT2:我看到 CDI 最佳实践说应该 add the @Vetoed annotation to all persistent entities 。目前,我的应用程序流控制是从 @MessageBean 到一系列 @Entity - 这是设计味道吗?

最佳答案

首先,您的任何实体都不在 Spring 应用程序上下文中,因此,Spring 的任何 Bean 都无法注入(inject)到您的实体中! 其次,如果您确实想这样做,请添加:

<context:spring-configured />

进入你的spring配置,然后在MyEntity类中添加@Configurable!

关于java - 在不使用@Inject/@EJB的情况下从@Entity访问@Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400362/

相关文章:

java - 如何查找String是否包含html数据?

java - CSV 导出器的输入流

java - @PostConstruct 第一次执行失败

architecture - 如何正确处理事件溯源中的聚合关系?

java - 保存聚合根而不暴露嵌套实体

java - 将我的应用程序的 http 请求重定向到 spring webflow 中的外部网站

java - 使用以下几个队列进行请求-回复

java - Java EE 的 Spring Security 之类的框架?

java - 带有实体类的 SOAP

java - DDD 中如何与聚合相关的低争用事务?