我正在使用领域驱动设计(我认为!)并且我需要访问一些全局属性。我有我的@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...
}
}
但是,这不起作用 - props
是 null
,无论如何网站告诉我 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/