【发布时间】: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.");
}
}
【问题讨论】: