使用Spring

时间:2017-01-24 13:54:44

标签: spring

我们已经有一个设置,我们正在加载文件,如:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
             <value>file:${AN_ENV_CONFIGURED_DIR}/project.properties</value>
    </list>
  </property>

配置文件位于服务器的单独位置。我想动态加载配置文件,如果有变化。既然我已经有了这个设置,那么有一种简单的方法可以从Spring重新加载配置文件,而不是使用TimerTask,如果它是唯一的方法,那么它仍然不足以立即加载文件。

2 个答案:

答案 0 :(得分:1)

您可以使用abc,以下是代码段。

ReloadableResourceBundleMessageSource

了解更多信息:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html

答案 1 :(得分:0)

使用以下bean每1秒重新加载config.properties。

@Component
public class PropertyLoader {

    @Autowired
    private StandardEnvironment environment;

    @Scheduled(fixedRate=1000)
    public void reload() throws IOException {
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> resourcePropertySource = propertySources.get("class path resource [config.properties]");
        Properties properties = new Properties();
        InputStream inputStream = getClass().getResourceAsStream("/config.properties");
        properties.load(inputStream);
        inputStream.close();
        propertySources.replace("class path resource [config.properties]", new PropertiesPropertySource("class path resource [config.properties]", properties));
    }
}

您的主配置看起来像:

@EnableScheduling
@PropertySource("classpath:/config.properties")
public class HelloWorldConfig {
}

然后访问该地区:

@Autowired
private Environment environment;

environment.get("my.property");