Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring override properties at runtime and keep them persistent

I am using Spring 3.2.8 and keep my settings in a properties file. Now I want some of them override at runtime. ​​I want to keep the new values persistent by overwriting the old values in the properties file​​.

How can I do this in Spring? Some properties ​​I inject with @ Value and others get with MessageSource.getMessage(String, Object [], Locale). The beans are already instantiated with these values​​. How can I access the properties, store them and update all beans system wide?

Thanks!

like image 297
Robert Moszczynski Avatar asked Nov 11 '22 08:11

Robert Moszczynski


1 Answers

OK, given your follow up answers I would keep this fairly simple and use what you already know of Spring. I'll make some assumptions that annotation configuration is OK for you.

In my example, I'll assume all the properties that you want to configure relate to something called a ServerConfiguration and that initially these are read from server.properties on the classpath.

So part 1, I would define a bean called ServerProperties that has the original values from the server.properties injected into it.

So:

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

     ...

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

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

}

Secondly, anywhere that relies on these properties, I would inject an instance of ServerProperties rather than using @Value e.g:

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

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

Thirdly I would expose a simple Controller into which ServerProperties is injected so that you can use your web page to update system properties e.g:

@Controller
public class UpdateProperties
{

    @AutoWired
    private ServerProperties serverProperties;        

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

Finally, I would use @PreDestroy on ServerProperties to flush the current property values to file when the ApplicationContext is closed e.g:

@Component
public class ServerProperties
{

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

That should give you a framework for what you need. I'm sure it can be tweaked, but it will get you there.

like image 59
Rob Blake Avatar answered Nov 14 '22 21:11

Rob Blake