在运行时中用@Value注释的更新字段 [英] Update field annotated with @Value in runtime

查看:445
本文介绍了在运行时中用@Value注释的更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在Spring中有这样一个组件:

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"/>  

并且myPropos.properties包含 someProperty 的值,该值将在初始化上下文时注入到 text 字段中.那非常简单容易.

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.

但是,假设我有一项服务,使用户可以更改 someProperty 的值:

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);

是否有可能我可以将newValue重新注入到文本字段中.我的意思是应该很简单.基本上,与初始化后注入没有什么不同.我无法想象Spring没有对此的支持?我可以引发一些事件或其他事情吗?

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?

我基本上可以自己完成此操作,但是我徘徊了,也许这已经存在了?如果不是,没有人知道一开始实际上是在处理什么Spring类的Spring类吗?如果不存在解决方案,我可能会重用那里的代码,由我自己执行.

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.

推荐答案

我希望spring没有对此的支持,因为正常的注入是在创建bean时完成的,但不会投入使用.

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.

无论如何:在此博客条目可重新加载的应用程序属性"中使用Spring 3.1,Java 7和Google Guava" ,您可以找到解决方案的主意.

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.

这篇关于在运行时中用@Value注释的更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆