java - 如何在运行时在 Tomcat 中创建一个 hibernate.properties 文件

标签 java hibernate tomcat

我有一个 Web 应用程序,它使用第 3 方提供的 jar 中包含的 servlet。 servlet 使用 hibernate.properties 来配置与数据库对话所需的 dB 设置。

这对我们来说是有问题的,因为每个环境的这个文件必须不同。我尝试创建一个模板文件并在上下文启动时生成真实文件。

文件生成有效,但应用程序在创建文件后找不到文件。如果我重新启动 tomcat,该应用程序可以正常工作,因为该文件自上次启动以来已经存在。

我不确定我是在与 java 还是 Tomcat 战斗,但我想知道为什么它无法在类路径中找到新创建的文件。

我也一直在寻找实际加载此文件但无法发现它的 hibernate 代码。查看它的加载方式可能会给我一些线索。

我的文件生成器看起来像:

public class HibernatePropertiesFileGenerator implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(HibernatePropertiesFileGenerator.class);

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        LOGGER.info("Generating hibernate.properties file.");
        Configuration configuration = new Configuration();
        configuration.setClassForTemplateLoading(this.getClass(), "/");
        configuration.setDefaultEncoding("UTF-8");
        configuration.setIncompatibleImprovements(new Version(2, 3, 20));

        Map<String, Object> freemarkerDataModel = Collections.singletonMap("env", (Object) context.getEnvironment());

        try {
            URL url = this.getClass().getResource("/hibernate.properties.ftl");
            File templateFile = new File(url.getFile());
            File outputFile = new File(templateFile.getParentFile(), "hibernate.properties");
            Template template = configuration.getTemplate("hibernate.properties.ftl");
            FileWriter fileWriter = new FileWriter(outputFile);
            template.process(freemarkerDataModel, fileWriter);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create hibernate.properties file.", e);
        }
        LOGGER.info("hibernate.properties file generated.");
    }
}

最佳答案

生成模板不起作用,因为 hibernate 实际上在 org.hibernate.cfg.Environment 的静态类初始化程序中读取 hibernate.properties。在创建我的文件时,此代码已经运行。

我已经通过对 hibernate.cfg.xml 文件进行模板化并放弃 hibernate.properties 文件来解决这个问题。

关于java - 如何在运行时在 Tomcat 中创建一个 hibernate.properties 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23402643/

相关文章:

java - 在java中拆分解析文本文件

java 调试 - 观察超出范围的变量

spring - 基本 spring hibernate struts2 应用程序的 Maven 原型(prototype)

mysql - Hibernate 在一次查询中选择相关数据

Codeigniter 和 Tomcat 集成

java - 如果我们在 Google Cloud Platform 中部署了 Spring Boot 应用程序,如何查看日志?

java - Vertx,多线程是如何工作的

java - 如何使用同步线程将数据插入到我的数据库表中

java - 错误 StatusLogger 无法识别格式说明符

java - Cpanel 和 Tomcat 7 servlet 映射