-->

Error when creating bean with type java.io.File [A

2019-06-15 07:24发布

问题:

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.

回答1:

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>


回答2:

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!