在运行时将动态属性应用于Bean [英] Apply dynamic properties to a bean at runtime

查看:79
本文介绍了在运行时将动态属性应用于Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Bean对话框,具有高度和宽度的属性:

Assume I have a bean DialogBox, with properties for height and width:

public class DialogBox {
 int x;
 int y;
 ...
}

在我的applicationContext.xml中,我将属性定义为合理的默认值:

In my applicationContext.xml I would define properties as reasonable defaults:

<bean id="dialogbox" class="DialogBox">
  <property name="x" value="100"/>
  <property name="y" value="100"/>
</bean>

我们有多个使用dialogBox bean的客户端,每个客户端都想要一个x和y的自定义值.我们讨论的一种方法是拥有多个属性文件,每个客户端一个属性文件,并且将客户端ID映射到适当的文件,例如,客户端123将映射到dialogbox_123.properties:

We have multiple clients that use the dialogBox bean, and each wants a custom value for x and y. One route we have discusses is having multiple properties files, one for each client, and have the client id map to the proper file, for example client 123 would map to dialogbox_123.properties:

dialogbox_123.properties:
x=200
y=400

然后在运行时,当请求Bean时,spring将查看是否为客户端存在定制属性文件,并使用这些属性,否则使用默认值.我知道PropertyOverrideConfigurer,但是AFAIK仅在启动上下文时有效,因此对于我们的目的不起作用.春天有没有现成的设施可以实现这一目标,或者有人可以推荐另一种方式?

Then at runtime when the bean is requested, spring would look to see if a custom properties file exists for the client, and use those properties, otherwise use the defaults. I am aware of the PropertyOverrideConfigurer, but AFAIK this only works when the context is started so will not work for our purposes. Is there an existing facility in spring to achieve this, or can someone recommend another way?

推荐答案

  1. 使用,以便每次需要一个实例时,都应创建一个新实例.
  2. 如果要将prototype bean注入到singleton bean中,请使用lookup-method(
  1. Use FactoryBean (as already suggested) to customize instantiation.
  2. set scope="prototype" on the bean, so that each time an instance is required, a new one should be created.
  3. In case you want to inject the prototype bean into a singleton bean, use lookup-method (Search for lookup-method here)

我不确定这是否适合您的情况.另一个建议是:

I'm not sure if this would fit your case though. Another suggestion would be:

在各种客户端"的@PostConstruct方法中,根据需要在已注入的对话框窗口中设置属性.喜欢:

In @PostConstruct methods of your various "clients" set the properties as desired on the already injected dialog window. Like:

public class MyDialogClient {
    @Autowired
    private Dialog dialog;

    @PostConstruct
    public void init() {
        dialog.setWidth(150); //or read from properties file
        dialog.setHeight(200);
    }
    ...
}

同样,在这种情况下,您可以使用scope凌辱.

Again, in this case, you can play with the scope atrribute.

这篇关于在运行时将动态属性应用于Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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