In Spring, “Autowiring by AutoDetect“, means chooses “autowire by constructor” if default constructor (argument with any data type), otherwise uses “autowire by type“.

See an example of Spring “auto wiring by autodetect”. Auto wiring the “kungfu” bean into “panda”, via constructor or type (base on the implementation of panda bean).

	<bean id="panda" class="com.tuts.heomi.netmon.Panda" autowire="autodetect" />
		
	<bean id="kungfu" class="com.tuts.heomi.netmon.KungFu" >
		<property name="name" value="Shao lin" />
	</bean>

1. AutoDetect – by Constructor

If a default constructor is supplied, auto detect will chooses wire by constructor.

package com.tuts.heomi.netmon;

public class Panda {
	private KungFu kungfu;

	public Panda(KungFu kungfu) {
		System.out.println("autowiring by constructor");
		this.kungfu = kungfu;
	}
	
	public KungFu getKungfu() {
		return kungfu;
	}

	public void setKungfu(KungFu kungfu) {
		System.out.println("autowiring by type");
		this.kungfu = kungfu;
	}

	@Override
	public String toString() {
		return "Panda [kungfu=" + kungfu + "]";
	}

}

Output

autowiring by constructor
Person [kungfu=KungFu [name=Shao lin]]

2. AutoDetect – by Type

If a default constructor is not found, auto detect will chooses wire by type.

package com.tuts.heomi.netmon;

public class Panda {
	private KungFu kungfu;

	public KungFu getKungfu() {
		return kungfu;
	}

	public void setKungfu(KungFu kungfu) {
		System.out.println("autowiring by type");
		this.kungfu = kungfu;
	}

	@Override
	public String toString() {
		return "Panda [kungfu=" + kungfu + "]";
	}

}

Output

autowiring by type
Person [kungfu=KungFu [name=Shao lin]]

Download Source Code

$ git clone https://github.com/favtuts/java-spring-tutorials.git
$ cd SpringAutoWiringByAutoDetect

References

  1. Spring Autowiring by Type
  2. Spring Autowiring by Constructor
  3. Spring Autowiring @Qualifier example
  4. Spring Auto-Wiring Beans
  5. Spring Auto-Wiring Beans with @Autowired annotatio…
  6. Spring Autowiring by Name
  7. Spring Autowiring by Type

Leave a Reply

Your email address will not be published. Required fields are marked *