Autowiring In Spring

Declaring each and every object we need to use in a spring based application can get very tedious. To avoid this, we can utilize Spring’s automatic bean wiring features. With automatic wiring, Spring can discover and wire beans automatically.

Spring automatic wiring works in two ways:

  • Component Scanning: Spring scan for beans defined in the application context.
  • Autowiring: Spring automatically injects dependencies to beans.

Component Scanning

Any class that is needed to be initialized via spring component scanning should be annotated with @Component.

Spring should know where to scan for components. We can specify this information in the applicationContent.xml using the below xml snippet:

<context:component-scan base-package="cubearticle.examples"/>

Or if we are using java config we can use the @ComponentScan annotation.

Autowiring

Spring looks for @Autowired annotation in the classes to inject their dependencies into them.


Sample Code:

Shown below are some sample classes that we will be using to showcase Spring automatic wiring:

We will start with a simple Vehicle interface that contains a method called drive(), to drive the vehicle. Next we will create an implementation of the Vehicle, the Car class.

package cubearticle.examples;

public interface Vehicle {
    public void drive();
}
package cubearticle.examples;

import org.springframework.stereotype.Component;

@Component
public class Car implements Vehicle{
    
    private String brand = "Audi";
    private String model ="R8";
    
    public void drive(){
        System.out.println("Driving "+brand+" "+model);
    }    
}

Notice that the Car class above is annotated with @Component, so that Spring can understand that the class is a Spring component and a bean must be created for this class. 

By default the bean will be given an id as 'car', which is derived by lowering the first letter in the class name. If we want to have a different id, we can pass the desired id as a value to the @Component annotation as shown in the Driver class.

Now that we have our Car ready, we need a driver to drive it. We will create a Driver class as shown below:

package cubearticle.examples;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("carDriver")
public class Driver {

    @Autowired
    private Vehicle car;
    
    public void drive(){
        car.drive();
    }
}

Notice the @Autowired annotation in the Driver class above. This is used to signal Spring to inject any bean with id car (name of the field annotated) to this property. The bean id for the Car class we created earlier was ‘car’. The same bean will be injected into this Driver class.

We will be using the Java class below to configure our beans. Notice that the class is completely empty other than the two annotations @Configuration and @ComponentScan. Our beans will be discovered and wired automatically using autowiring features.

package cubearticle.examples;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class Config { }

Since we did not provided any attributes with @ComponentScan, Spring will by default scan in the same package as that of the Configuration class. To specify a different package, we can specify the package name in the value attribute. To scan multiple packages we can use the basePackages attribute as shown below:

@ComponentScan("cubearticle.examples.autowiring")
@ComponentScan(basePackages={"cubearticle.examples.autowiring","cubearticle.examples.spring.autowiring"})

We will use the Main class below to test our example code. Here we use the AnnotationConfigApplicationContext to create our application context and use it to get the carDriver bean. Finally we call the drive() method of the Driver class. 

package cubearticle.examples;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String arg[]){
        ApplicationContext cntx = new AnnotationConfigApplicationContext(Config.class);
        Driver driver = (Driver)cntx.getBean("carDriver");
        driver.drive();
    }
}

On executing our main class above we would get the following output on console:

Driving Audi R8

Download Source Code

You can download the source code of the examples discussed in this article.

POPULAR ARTICLES

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article