Spring overrides properties at runtime and keeps them constant

I use Spring 3.2.8 and save my settings in a properties file. Now I want some of them to be redefined at runtime. I want the new values ​​to be saved by overwriting the old values ​​in the properties file.

How to do it in Spring? Some properties that I insert @ Value, while others get using MessageSource.getMessage(String, Object [], Locale). beans are already created with these values. How can I access the properties, save them and update the entire beans system?

Thank!

+4
source share
1 answer

, , , Spring. , .

, , , , ServerConfiguration, server.properties .

, 1, bean, ServerProperties, 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.
    }
}

, . , , .

0

Source: https://habr.com/ru/post/1539416/


All Articles