Spring Autowired Constructor Caveats

Here’s a little quiz about Spring autowiring. Given the following classes:

public class RightService {
    //...
}

public class WrongService {
    //...
}

public class MyBean {

    @Autowired
    public MyBean(RightService service) {
        //...
    }
}

and the following Spring beans definitions:

  <context:annotation-config/>

  <bean id="rightService" class="RightService"/>
  <bean id="wrongService" class="WrongService"/>

  <bean id="myBean" class="MyBean">
    <constructor-arg ref="wrongService"/>
  </bean>

what do you think will happen when starting the context?

  1. The Spring context fails to start saying that a constructor-arg of type RightService was expected but WrongService was supplied instead.
  2. The Spring context fails to start saying that it cannot find a constructor MyBean(WrongService).
  3. The Spring context starts up and works just fine.

Surprisingly enough, the correct answer is 3. (Tested with Spring 3.0.6.) Since an instance of RightService is found in the context that one is used for creating MyBean. That makes sense because by default Spring autowires by type.

However – and this is the really surprising bit – the supplied WrongService constructor-arg is simply ignored. Apparently when mixing an @Autowired constructor with construct-args in the XML any args are not actually used are just silently discarded, without any errors or even warnings.

An error will be triggered if constructor-arg indexes are specified:

  <bean id="myBean" class="MyBean">
    <constructor-arg index="0" ref="wrongService"/>
  </bean>

Unsatisfied dependency expressed through constructor argument with index 0…

The bottom line is: better don’t mix @Autowired with constructor-args, the results are difficult to understand and thus error-prone.

One thought on “Spring Autowired Constructor Caveats

  1. Good to learn that Spring will silently ignore that constructor arg. Is there any way to make Spring fail violently rather than silently?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s