3

我将属性文件加载到一个类,然后在整个应用程序中使用该类来获取它们。

public class PropertiesUtil extends PropertyPlaceholderConfigurer {

    private static Map<String, String> properties = new HashMap<String, String>();

    @Override
    protected void loadProperties(final Properties props) throws IOException {
        super.loadProperties(props);
        for (final Object key : props.keySet()) {
            properties.put((String) key, props.getProperty((String) key));
        }
    }

    public String getProperty(final String name) {
        return properties.get(name);
    }

}

并在 ApplicationContext.xml

    <bean id="propertiesUtil"
        class="com.test.PropertiesUtil">
        <property name="locations">
            <list>
                <value>classpath:test/test.properties</value>
            </list>
        </property>
    </bean>

现在我想确保属性文件在更改时重新加载。

我有一个与 tomcat 服务器一起初始化的侦听器类。我已经为文件观察器编写了以下逻辑

TimerTask task = new FileWatcher(new File("c:\\temp-reb\\config\\config.properties")) {
    /*
     * (non-Javadoc)
     * @see com.belgacom.rosy.rebecca.utils.FileWatcher#onChange(java.io.File)
     */
    @Override
    protected void onChange(File file) {
        loadServiceProperties(file);
        loadMetadata();
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), Long.valueOf(properties.getProperty("properties.file.timer.schedule"))); // repeat the check every second

问题是

  1. FileWatcher 需要运行路径,我不想硬编码
  2. 我如何告诉 spring 调用属性以显式重新加载!
4

2 回答 2

3
  1. FileWatcher 需要运行路径,我不想硬编码

只需提供相对路径,如同一项目文件夹中的资源目录,您可以使用该getResource()方法获取。您还可以使用系统属性访问就像user.dir使用工作目录一样。

File f = new File(System.getProperty("user.dir")+ "/test.properties");
System.out.println(f.getAbsolutePath());

2.我如何告诉spring调用属性来显式地重新加载!

你目前的做法对我来说似乎没问题。可能还有其他方法,但我认为上述过程没有任何缺陷。

于 2012-12-11T06:48:59.833 回答
1

这是一条蜿蜒曲折的道路,通往真正黑暗的地方。Spring 根据定义实例化并维护对单例的引用。因此,如果客户端注入了依赖项并保留它,并且应用程序上下文开始提供新的 bean,那么您将处于一个非常丑陋的状态。如果您不将属性用作 bean 属性,则应该没问题,但是混合这并不是真正的方法。

如果有的话,我会尝试限制受重新加载属性影响的 bean 数量并将它们放在特殊范围内。这样,每当您的范围发生变化时,您都会获得一个具有最新配置的新 bean。至少您将拥有已定义的属性生命周期,并且确切地知道您要面对什么。

于 2012-12-11T07:19:05.247 回答