Rahul Raj
Rahul Raj

Reputation: 3459

Spring Autowiring autodetect

I want to clarify about this:

Regarding Autowiring "autodetect"

In some resources, I found if "Default constructor is found, then "auto wiring constructor" applies. If not "auto wiring by type" applies.

And in some resources, I found if "Default constructor is found, then "auto wiring by type" applies. If not "auto wiring constructor" applies.

can anyone confirm which is the right one? confused with this.

Upvotes: 3

Views: 6045

Answers (2)

MiDhuN
MiDhuN

Reputation: 232

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in .

<bean id="customer" class="com.midhun.common.Customer" autowire="byName" />

In Spring, 5 Auto-wiring modes are supported.

1.no – Default, no auto wiring, set it manually via “ref” attribute

2.byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.

3.byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.

4.constructor – byType mode in constructor argument.

5.autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.

No, you are not required to use default (no arg) constructors. If there is no constructor defined in bean it will chose it, if u want you can use .. the type of auto wiring dependent up on your requirements

@Qualifier can also help you to specify your injection

you can youse @Quanlifier to tell Spring about which bean should autowired.

package com.midhun.pgm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Customer {

    @Autowired
    @Qualifier("personA")
    private Person person;
    //...

}

Upvotes: 4

Sai prateek
Sai prateek

Reputation: 11906

There should be no confusion in this.

Autowiring by autodetect uses either of two modes i.e. constructor or byType modes. First it will try to look for valid constructor with arguments, If found the constructor mode is chosen. If there is no constructor defined in bean, or explicit default no-args constructor is present, the autowire byType mode is chosen.

Upvotes: 1

Related Questions