Spring在运行时覆盖属性并保持持久性

时间:2014-05-06 10:03:37

标签: java spring spring-mvc

我正在使用Spring 3.2.8并将我的设置保存在属性文件中。现在我希望它们中的一些在运行时覆盖。我希望通过覆盖属性文件中的旧值来保持新值的持久性。

我怎样才能在春天这样做?我使用@ Value注入的某些属性和其他属性MessageSource.getMessage(String, Object [], Locale)。 bean已经使用这些值进行了实例化。如何访问属性,存储它们并更新系统范围内的所有bean?

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,根据你的后续答案,我会保持这个相当简单并使用你已经知道的Spring。我会假设注释配置适合你。

在我的示例中,我假设您要配置的所有属性都与名为ServerConfiguration的内容相关,并且最初这些属性是从类路径上的server.properties读取的。

所以第1部分,我将定义一个名为ServerProperties的bean,它具有注入其中的server.properties的原始值。

所以:

@Component
public class ServerProperties
{
     @Value("${server.ip}");
     private String ipAddress;

     ...

     public void setIpAddress(String ipAddress)
     {
        this.ipAddress = ipAddress;
     }

     public String getIpAddress()
     {
        return this.ipAddress;
     }

}

其次,在依赖于这些属性的任何地方,我会注入ServerProperties的实例,而不是使用@Value,例如:

@Component
public class ConfigureMe
{
    @AutoWired
    private ServerProperties serverProperties;

    @PostConstruct
    public void init()
    {
        if(serverProperties.getIpAddress().equals("localhost")
        {
            ...
        }
        else
        {
            ...
        }
    }
}

第三,我会公开一个注入Controller的简单ServerProperties,以便您可以使用您的网页更新系统属性,例如:

@Controller
public class UpdateProperties
{

    @AutoWired
    private ServerProperties serverProperties;        

    @RequestMapping("/updateProperties")
    public String updateProperties()
    {
       serverProperties.setIpAddress(...);
       return "done";
}

最后,我会在@PreDestroy上使用ServerProperties在ApplicationContext关闭时将当前属性值刷新为文件,例如:

@Component
public class ServerProperties
{

    @PreDestroy
    public void close()
    {
        ...Open file and write properties to server.properties.
    }
}

这应该为您提供所需内容的框架。我确定它可以调整,但它会让你到那里。