Spring Autowiring by Constructor

In Spring, “Autowiring by Constructor” is actually autowiring by Type in constructor argument. It means, if data type of a bean is same as the data type of other bean constructor argument, auto wire it.

See a full example of Spring auto wiring by constructor.

1. Beans

Two beans, developer and language.


package com.mkyong.common;

public class Developer {
	private Language language;

	//autowire by constructor
	public Developer(Language language) {
		this.language = language;
	}

	//...

}

package com.mkyong.common;

public class Language {
	private String name;
	//...
}

2. Spring Wiring

Normally, you wire the bean via constructor like this :


	<bean id="developer" class="com.mkyong.common.Developer">
		<constructor-arg>
			<ref bean="language" />
		</constructor-arg>
	</bean>
		
	<bean id="language" class="com.mkyong.common.Language" >
		<property name="name" value="Java" />
	</bean>

Output


Developer [language=Language [name=Java]]

With autowire by constructor enabled, you can leave the constructor property unset. Spring will find the compatible data type and wire it automatcailly.


	<bean id="developer" class="com.mkyong.common.Developer" autowire="constructor" />
		
	<bean id="language" class="com.mkyong.common.Language" >
		<property name="name" value="Java" />
	</bean>

Output


Developer [language=Language [name=Java]]

Download Source Code

References

  1. Spring DI via constructor
  2. Spring Autowiring by Type

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
Lekhraj Dinkaryogesh murdeshwarFirozClaudioSpring Autowiring by AutoDetect Recent comment authors
newest oldest most voted
yogesh murdeshwar
Guest
yogesh murdeshwar

I think its autowiring byName in constructor

It doesn’t throw any exception when there are multiple beans with property type constructor and only bean whose id matches with property name is injected.

Lekhraj Dinkar
Guest
Lekhraj Dinkar

I agree to it. I tried same in spring 4.0.3. Hoping the same behaviour in versions.

Firoz
Guest
Firoz

Hi MKYong,
You have fixed the constructor value here using the XML. What if I have to pass a dynamic value in constructor ?
Is there anyway to do this using annotations like @Autowire and @Value?

Claudio
Guest
Claudio

Is there anyway to do this using only annotations?
Actually I only can do this if I use: context.getBean(beanName, new Object[]{req, resp, params});

Big Hug.

trackback
Spring Autowiring by AutoDetect

[…] 2011 , Author: mkyongprintIn Spring, “Autowiring by AutoDetect“, means chooses “autowire by constructor” if default constructor (argument with any data type), otherwise uses “autowire by […]