【问题标题】:How to create a hibernate.properties file at runtime in Tomcat如何在运行时在 Tomcat 中创建 hibernate.properties 文件
【发布时间】:2014-05-01 05:40:38
【问题描述】:

我有一个 Web 应用程序,它使用了一个 servlet,该 servlet 包含在由第 3 方提供的 jar 中。 servlet 使用 hibernate.properties 来配置与 DB 通信所需的 dB 设置。

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

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

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

我也一直在寻找实际加载此文件的休眠代码,但找不到它。看看它的加载方式可能会给我一些线索。

我的文件生成器如下所示:

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.");
    }
}

【问题讨论】:

    标签: java hibernate tomcat


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多