Error when creating bean with type java.io.File [Ambiguous constructor argument types]

cyber-monk picture cyber-monk · Sep 7, 2011 · Viewed 29.6k times · Source

I have the following spring bean configuration

  <bean id="fileBean" class="java.io.File">
    <constructor-arg type="java.lang.String" 
                     value="$prop{file.path.property}" />    
  </bean>

I'm getting the following error

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'fileBean' defined in class path resource [context.xml]:  
Unsatisfied dependency expressed through constructor argument with index 0 of type
[java.net.URI]: Ambiguous constructor argument types - did you specify the correct 
bean references as constructor arguments?

There is only one constructor for java.io.File with a single String parameter so I'm not sure why this is ambiguous. Any help appreciated.

Answer

cyber-monk picture cyber-monk · Sep 7, 2011

Found this link that explains what is happening. It turns out that spring will match arguments by type if there is no argument index specified. In this case spring takes my single String argument and passes it to java.io.File constructor that takes TWO strings. This can be fixed by specifying the constructor-arg index.

<bean id="fileBean" class="java.io.File">
  <constructor-arg index="0"
                   type="java.lang.String" 
                   value="$prop{file.path.property}" />    
</bean>