开发者

Spring 3.x PropertyOverrideConfigurer insists on using set, not constructor

Trying to use Spring PropertyOverrideConfigurer or some such subclass, to help create the following bean:

public class Foo {
  private final String name;

  public Foo(String name) { this.name = name; }

  public String getName() { return name; }
}

Suppose my bean definition is something like

<bean id="foo" class="Foo">
  <constructor-arg name="name" value="abc">
</bean>

I've handed Spring a file foo.properties, in there it finds an entry foo.name="def"

So the default name property for Foo bean is "abc", I want it overriden to be "def"; HOWEVER I do not want to have an explicit setName(String name) method hanging off my Foo class, since despite what Spring thinks I consider this a terrible idea in software development. I expect Spring to be able to pass the overridden value as "def" to the constructor of Foo, not call Foo later with setName("def").

I have not gotten this to work, is there a way? The only success I've had is to add the method

 public void setName(String name) { this.name = name; }

to the Foo class, which again I think is a terrible idea sinc开发者_运维百科e it opens up your class for unintentional side-effecting later.

Is there any hope? Can I modify the bean definition somewhere before Spring creates Foo with the (wrong) "abc" name?


You can definitely do it. You xml should look somewhat like:

<bean id="foo" class="Foo">
   <constructor-arg index="0" value="abc"/>
</bean>

Assuming that constructor has one parameter and "abc" is a value coming from your property file. In this case the setter is not needed.

More information is available in Spring documentation at http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-factory-collaborators

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜