如何在不重新启动Tomcat的情况下重新加载属性文件 [英] How to reload properties file without rebooting Tomcat
问题描述
我使用以下方法从类路径中加载属性文件:
I load a property file from classpath with the method :
String cheminFichier = new StringBuilder(100).append(classeBP.getPackage().getName().replace(".", "/")).append(File.separator).append(
REPERTOIRE_MAPPING).append(nomFichier).append(".properties").toString();
InputStream isMapping = Thread.currentThread().getContextClassLoader().getResourceAsStream(cheminFichier.toString());
if (isMapping == null)
{
throw new ServiceMappingException("Erreur lors du chargement du mapping du service. Le fichier "
+ cheminFichier + " n'existe pas.");
}
else
{
Properties mapping = new Properties();
try
{
mapping.load(isMapping);
}
catch (IOException e)
...
}
好的,可以.但是,如果在Tomcat运行时修改属性文件的内容,则更改将被忽略.它没有像类一样被热重载.
Ok, it's work. But if I modify the content of the property file when Tomcat is running, changes are ignored. It's not hot-reloaded as with classes.
我的上下文是使用 reloadable ="true"
选项配置的,并且Thread.currentThread().getContextClassLoader()返回的类加载器是WEBAPP类加载器(不是系统类加载器或其他类).
My context is configured with reloadable="true"
option and the classloader returned by Thread.currentThread().getContextClassLoader() is the WEBAPP classloader (not the system classloader or other).
我读到可以使用ServletContext.getResourceAsStream,但是我无法访问Servlet上下文.
I read it's possible to use ServletContext.getResourceAsStream, but I haven't access to the servlet context.
这是Tomcat 5.5.
It's Tomcat 5.5.
有什么主意吗?如果没有,您是否有一种解决方案,可以强制重新加载特定资源(我的属性文件)?
Any idea ? If not, do you have a solution for forcing to reload a specific resource (my property file) ?
谢谢!
推荐答案
实际上,您的Web应用确实可以在各个点访问ServletContext.例如,您可以使用 ServletRequest.getServletContext()
或通过 ServletContextListener
回调获得的 ServletContextEvent
来获取它.
Actually, your webapp does have access to the ServletContext at various points. For example you can get it using ServletRequest.getServletContext()
, or from a ServletContextEvent
obtained via a ServletContextListener
callback.
这是个有点题外话,但是您应该意识到这段代码:
This is a bit off topic, but you should realise that this code:
String cheminFichier = new StringBuilder(100).append(classeBP.getPackage().getName().replace(".", "/")).append(File.separator).append(
REPERTOIRE_MAPPING).append(nomFichier).append(".properties").toString();
可以/应该写为:
String cheminFichier = classeBP.getPackage().getName().replace(".", "/")) +
File.separator + REPERTOIRE_MAPPING + nomFichier + ".properties";
在此处明确使用 StringBuilder
时,在此处没有性能优势,因为Java编译器会将连接编译为相同的代码.
There is no performance advantage here in explicitly using a StringBuilder
here, because the Java compiler will compile the concatenation to the same code.
如果串联涉及循环,则只需使用 StringBuilder
.
You only need to use a StringBuilder
if the concatenation involves a loop.
这篇关于如何在不重新启动Tomcat的情况下重新加载属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!