Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update field annotated with @Value in runtime

Let's imagine we have such a component in Spring:

@Component
public class MyComponent {

    @Value("${someProperty}")
    private String text;
}

If we define the property placeholder:

<context:property-placeholder location="classpath:myProps.properties"/>  

And myPropos.properties contains the value for someProperty the value will be injected to the text field when the context is initialized. That's quite simple and easy.

But let's say that I have a service that enables user to change the value of the someProperty:

public void changeProp(String name, String newValue);

Is there a chance I can re-inject the newValue to text field. I mean it should be quite straight forward.. Basically it's nothing different than the after-initialization injection. I can not imagine that Spring does not have support for this? Can I fire some event or something?

I could do this on my own basically, but I wander is it maybe something there already? If not does anyone know what Spring class is in fact handling the injections at the first place? I could probably reuse the code there do perform this on my own if a solution does not exists.

like image 351
Ivan Senic Avatar asked Apr 13 '26 19:04

Ivan Senic


1 Answers

I expect spring does not have a support for this, because the normal injection is done while creating the bean, but not will it is put in service.

Anyway: in this blog entry "Reloadable Application Properties with Spring 3.1, Java 7 and Google Guava", you can find the idea for an solution.

The key idea is to use a post processor to build a list of all fields with property fields. And if the properties are changed on can use this list to update the fields.

like image 148
Ralph Avatar answered Apr 16 '26 13:04

Ralph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!