Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 299
cyber-monk Avatar asked Sep 06 '11 23:09

cyber-monk


2 Answers

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>
like image 162
cyber-monk Avatar answered Oct 04 '22 02:10

cyber-monk


Just my two cents here: I had the exact same problem today. I have a unit test to check if Spring can read my XML config and generate all necessary beans. It was failing because I was editing the wrong XML file. I was editing a "dist" version from an Ant build, instead of the correct version from source control.

Lesson learned: Read those Spring exception messages (with XML file paths) very closely!

like image 44
kevinarpe Avatar answered Oct 04 '22 01:10

kevinarpe