user3457336
user3457336

Reputation:

Spring Instantiation exception with java.lang.String

What is wrong with the below bean? Using spring-beans-2.0 I'm getting below exception:

<bean id="logger" class="java.lang.String">
      <constructor-arg value="logger"/>
</bean>

logger bean ibjecting to :

<bean id="loggerType" class="java.lang.String" scope="prototype">
    <constructor-arg value="logger" />
</bean>

loggerbean injecting other bean that is correctly have argument as "java.lang.String".

Exception

Could not instantiate bean class [java.lang.String]: Illegal arguments for constructor; 
  nested exception is java.lang.IllegalArgumentException:    
  java.lang.ClassCastException@5083198c

Upvotes: 0

Views: 589

Answers (2)

mike_m
mike_m

Reputation: 1546

String class has many one-argument constructors so Spring could choose wrong one, hence the exception.

I doubt it happens in newer versions of Spring. You said that you use Spring 2 and there is a bug related to this. But it seems to be fixed in newer versions.

The bug report says that it is fixed in version 3.0.3.

Upvotes: 0

Braj
Braj

Reputation: 46881

If you are injecting another bean then use ref attribute instead of value attribute.

<bean id="loggerType" class="java.lang.String" scope="prototype">
    <constructor-arg ref="logger" />
</bean>

Or use <ref/> tag with bean as attribute

<bean id="loggerType" class="java.lang.String" scope="prototype">
    <constructor-arg>
        <ref bean="logger"/>
    </constructor-arg>
</bean>

For more info have a look at Spring documentation References to other beans (collaborators)

I suggest to move latest version of Spring - 4.0.6.RELEASE

Upvotes: 1

Related Questions