用于存储应用程序设置的Java/JPA类
如何使用JPA为Java Servlet应用程序创建用于存储应用程序设置的Java/JPA类,java,jpa,servlets,Java,Jpa,Servlets,如何使用JPA为Java Servlet应用程序创建设置类?我想到的是一个静态类,它有一个键/值对映射,用于存储应用程序设置,如电子邮件服务器地址等。类似这样: public class ApplicationSettings { private static Map<String, String> settings; 公共类应用程序设置{ 私有静态地图设置; 用于基于Spring的应用程序 您可以使用缓存存储数据库中的属性。您可以使用@Cacheable(“proper
设置
类?我想到的是一个静态类,它有一个键/值对映射,用于存储应用程序设置,如电子邮件服务器地址等。类似这样:
public class ApplicationSettings {
private static Map<String, String> settings;
公共类应用程序设置{
私有静态地图设置;
用于基于Spring的应用程序
您可以使用缓存存储数据库中的属性。您可以使用@Cacheable(“properties”)
调用数据库服务并将其加载到缓存中。如果要更新、删除或添加新属性,可以使用@cacheexecute(value=“properties”,allEntries=true)
您可以调用数据库服务来执行实际操作。@cacheexecute
将清除为属性
键映射的所有现有缓存,并通过隐式调用@Cacheable(“属性”)
加载新属性
@Repository
public class ApplicationSettings {
private DatabaseService databaseService;
public ApplicationSettings(DatabaseService databaseService) {
this.databaseService = databaseService;
}
@Cacheable("properties")
public Map<String, String> getAppProperties() {
return databaseService.getAppProperties();
}
@CacheEvict(value = "properties", allEntries = true)
public void updateAppProperties(String key, String value) throws IOException {
databaseService.updateAppProperties(key, value);
}
}
用于基于Servlet的应用程序
您可以使用EhCache或简单地使用Sevlet Listener来实现上述场景
在web.xml中
<web-app ....>
<listener>
<listener-class>
com.listernerpackage.ApplicationInitializationListener
</listener-class>
</listener>
:
com.listernerpackage.ApplicationInitializationListener
:
创建ServletContextListener
public class ApplicationInitializationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
Map<String, String> properties = someDbManager.getAppProperties();
context.setAttribute("properties", properties );
}
}
公共类ApplicationInitializationListener实现ServletContextListener{
@凌驾
公共void contextInitialized(ServletContextEvent事件){
ServletContext=event.getServletContext();
Map properties=someDbManager.getAppProperties();
setAttribute(“属性”,属性);
}
}
您可以通过调用
Map<String, String> properties = (Map<String, String>) this.getContext().getAttribute("properties");
Map properties=(Map)this.getContext().getAttribute(“属性”);
为什么不能使用属性或ymlconfigurations@NidhishKrishnan我想将设置保存到数据库中,以便在应用程序更新期间保留这些设置。好的,然后您可以将属性存储在数据库中,并在应用程序启动时将其加载到缓存中……这样,每次您都不需要加载道具来自数据库的erties(我希望属性始终保持不变)不,设置不是恒定的。它们可以由应用程序的管理员用户配置。这些配置会经常更改吗感谢Nidhish,我们将对此进行研究。我猜BookRepository来自其他地方。Nidish,您的回答似乎假设使用了Spring框架。我的应用程序不使用Spring。它是带JPA的纯Java Servlets。@geschema您可以使用ehcache或ServletContextListener……我已经更新了一个示例
Map<String, String> properties = (Map<String, String>) this.getContext().getAttribute("properties");