user3504187
user3504187

Reputation: 83

Unable to Autowire a bean of type String

I have a bean as defined below which I want to autowire in to a Class which is defined as a bean in the Spring context file. But its not working, Strangely the other object bean types autowired in the same class are being autowired correctly. Bean to Autowire is as below :-

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

Class where its to be Autowired is :- I have tried annotating it with @Component .But no success.

public class AService { 
  @Autowired 
  private BDao bDao; 

  @Autowired 
  private String stringToAutowire; 
   ........
 }

context file is as :-

<context:annotation-config/>
<context:component-scan base-package ="PKG "/>
<bean id="aService" class="AService"/>
<bean id="bDao" class="BDao"/>
<bean id="stringToAutowire" class="java.lang.String">
  <constructor-arg value="true" />
</bean>

Upvotes: 2

Views: 10121

Answers (3)

Goutam Kumar
Goutam Kumar

Reputation: 45

You can not autowire simple properties such as primitives, Strings, and Classes (and arrays of such simple properties) and explicit dependencies in property and constructor-arg settings always override autowiring.

So drop @Autowired annotation from stringToAutowire and use with property.

Upvotes: 0

CoreyOConnor
CoreyOConnor

Reputation: 490

In the Spring documentation:

There is this text "You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation is by-design."

I have not found an exact specification of what happens in this case. In my experience Autowire of String properties is unreliable. Sometimes works, sometimes not. So I recommend avoiding autowire of string values.

In your case you are using both Autowire and constructor-arg. They are separate mechanisms. Only one is required.

  1. Ditch Autowire for String.
  2. Add a constructor to AService that takes, as the first argument, a string to assign to "stringToAutowire". The "constructor-arg" will specify what to pass for this constructor argument.

Upvotes: 3

Prasad Khode
Prasad Khode

Reputation: 6739

try using below:

@Autowired
@Qualifier("stringToAutowire")
private String someString;

Upvotes: 0

Related Questions