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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With