Friday 18 March 2011

Autowiring in Spring

In a large application, all of explicit constructor or property wiring will make XML lengthy and hard to debug if anything needs to change in between.. Instead of explicitly wiring all of your bean’s properties, you can use Spring autowire features to wire the dependencies for you.
Spring provides the following four types of autowiring:-
  1. byName—Attempts to find a bean in the container whose name (or ID) is
    the same as the name of the property being wired. If a matching bean is not
    found, the property will remain unwired.
  2. byType—Attempts to find a single bean in the container whose type
    matches the type of the property being wired. If no matching bean is found,
    the property will not be wired. If more than one bean matches, an
    org.springframework.beans.factory.UnsatisfiedDependencyException
    will be thrown.
  3. constructor—Tries to match up one or more beans in the container with
    the parameters of one of the constructors of the bean being wired. In the
    event of ambiguous beans or ambiguous constructors, an org.springframework.beans.factory.UnsatisfiedDependencyException will be thrown.
  4. autodetect—Attempts to autowire by constructor first and then using
    byType. Ambiguity is handled the same way as with constructor and
    byType wiring.
By default @Autowired when used with constructor, will search for a bean of type the constructor parameter in the context. Example in case of FlightRepositoryImpl it refers to type -- DataSource.

By Name vs By Type
But suppose that we have more that one bean of the same type like for eg. we have multiple datasources then we will have to use the byName approach. In this case we will have to specify the name/id of the bean which we are explicitly referring to.  when @Autowired / @Resource is used at the field name or property level, it defaults to the by Name approach. 

Example :
Doing it at setter level :
package annotations;
@Repository
public class FlightRepositoryImpl {


private DataSource dataSource;

@Autowired @Qualifier("ds")
public void FlightRepositoryImpl (DataSource dataSource) {
this.dataSource = dataSource;
}
}
Or we can do this at field level :
package annotations;
@Repository
public class FlightRepositoryImpl {

@Autowired @Qualifier("ds")
private DataSource dataSource;

public void FlightRepositoryImpl (DataSource dataSource) {
this.dataSource = dataSource;
}
}

Autowiring in xml config.

No comments:

Post a Comment