开发者

Leaving out <constructor-arg/> in spring framework when there's a default parameter value

开发者 https://www.devze.com 2023-03-09 13:50 出处:网络
I have the following simple constructor: public SimpleClass(Type1 arg1, int interval = 1000) { ... } I\'m initialising this using the spring framework as follows, without using autowire:

I have the following simple constructor:

public SimpleClass(Type1 arg1, int interval = 1000)
{ ... }

I'm initialising this using the spring framework as follows, without using autowire:

<object name="SimpleClass" type="..., ...">     
    <constructor-arg name="arg1" ref="..." />
    <constructor-arg name="interval" value="1000" />    
</object>

My question is: Since I'm defining a default value for the second parameter in the actual constructor, c开发者_运维百科an I leave it out of the spring config file, or does spring need an explicit declaration for all parameters if you don't use autowire? Is there any point in leaving in a default parameter value here, since I'm using spring?


That does not work when using xml configuration (tested it with Spring.NET 1.3.1).

It probably does work when using CodeConfig, but I haven't tried it out.

Quickest work-around would be to simply introduce a second constructor in your class:

Class SimpleClass
{
  public SimpleClass(Type1 arg1) : this(arg1, 1000)
  {}

  public SimpleClass(Type1 arg1, int interval = 1000)
  { 
    // ...
  }
}

That will always work.

0

精彩评论

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