Java/JPA class for storing application settings

Viewed 145

How can I use JPA to create a Settings class for my Java Servlet application? I'm thinking of something like a static class with a map of key/value pairs for storing the application settings like e-mail server address etc. Something like this:

public class ApplicationSettings {

    private static Map<String, String> settings;
1 Answers

For Spring based application

You can use Caching for storing the properties from database. You can use @Cacheable("properties") for calling the database service and load it in the cache. If you want to update, delete or add new property you can use @CacheEvict(value = "properties", allEntries = true) where you can call the database service to use do the actual operation. @CacheEvict will clear all the existing cache mapped for properties key and loads the new properties by calling @Cacheable("properties") implicitly

@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);
    }
}

You can now use ApplicationSettings wherever want can the properties like

@Autowired
private ApplicationSettings applicationSettings;

:
:
Map<String, String> appProperties = applicationSettings.getAppProperties();

For Servlet based application

You can use EhCache or simply use Sevlet Listener for achieving the above scenario

in web.xml

<web-app ....>
  <listener>
    <listener-class>
    com.listernerpackage.ApplicationInitializationListener
    </listener-class>
  </listener>
:

Create a 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 );           
    }
}

You can retrieve the properties in servlet by calling

Map<String, String> properties = (Map<String, String>) this.getContext().getAttribute("properties");
Related