spring

Spring 4 Autowire Example

1. Introduction

Autowiring is method of creating an instance of an object and “by concept” injecting that instance on a specific class that uses it. By that, therefore creates a “wiring” of an instance to a class that will use it’s attributes. In Spring, when the application server initialize the context, it creates a stack/heaps of objects in it’s JVM container. These objects are available for consumption at any given time as long as the application is running (runtime).

Now once these objects are ready, they can now be injected to different classes that belongs on the same application context. In a standard Java application, we can use the ClassPathXmlApplicationContext class to create instances of the beans on the IoC container (JVM), making them available to be injected Or wired on any Java objects that needs it.

2. Usage of Autowire

In this example, I will show you how a bean is wired by create the classes (beans) inside the applicationContext.xml and using ClassPathXmlApplicationContext to create the object instance that will be used by our AppMain.java class.

Step by Step Implementation

2.1 Create the Application

Create the Java project. I would suggest using Maven so that we can easily get the dependency if needed.

Figure 1.0 New Maven Project
Figure 1.0 New Maven Project

2.2 Configure POM.xml (maven)

We need to add the spring dependency on our project. Add spring core and framework.

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jgc.areyes1.sample</groupId>
    <artifactId>spring-autowire-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
 
 
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
 
    <properties>
        <spring.version>4.1.6.RELEASE</spring.version>
    </properties>
</project>

2.3 Create Services

We then create the service that we will eventually define on the applicationContext.xml.

UserAccountService.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.javacodegeeks.areyes1.beans;
 
public class UserAccountService {
     
    public UserAccountService() {
        this.name = "Alvin Reyes";
        this.description = "Account is activated with enough funds for equity trading";
        this.details = "PHP10000.00";
    }
 
    private String name;
    private String description;
    private String details;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getDetails() {
        return details;
    }
    public void setDetails(String details) {
        this.details = details;
    }
     
}

2.4 Configure beans (applicationContext.xml)

We then create the applicationContext.xml inside the resources folder. This is for it exist on the classpath

applicationContext.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
 
    <context:annotation-config />
    <!-- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> -->
 
 
 
    <bean id="userAccountService" autowire="byName"  class="com.javacodegeeks.areyes1.beans.UserAccountService">
    </bean>
 
     
</beans>

2.5 Create the class that will use (injection) the service

Create the class that will call the beans. As you can see, we called the bean by name to get the instance of that object (cat and dog).

Want to master Spring Framework ?
Subscribe to our newsletter and download the Spring Framework Cookbook right now!
In order to help you master the leading and innovative Java framework, we have compiled a kick-ass guide with all its major features and use cases! Besides studying them online you may download the eBook in PDF format!

App.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.javacodegeeks.areyes1.main;
 
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.javacodegeeks.areyes1.beans.UserAccountService;
 
public class AppMain {
 
 
    private UserAccountService userAccountService;
     
    public AppMain() {
        ClassPathXmlApplicationContext context =  new ClassPathXmlApplicationContext("classpath*:/applicationContext.xml");
        UserAccountService userAccountService = (UserAccountService)context.getBean("userAccountService");
        System.out.println(userAccountService.getName());
        System.out.println(userAccountService.getDetails());
        System.out.println(userAccountService.getDescription());
         
        context.close();
    }
     
     
    public static void main(String[] args ) {
        new AppMain();
    }
}

2.6 Test it Out!

Run the AppMain.java and see it for yourself! You should see the following result

Figure 2.0 Results of running AppMain.java
Figure 2.0 Results of running AppMain.java

3. Download the Eclipse project of this tutorial:

Download
You can download the full source code of this example here : spring-autowire-sample
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Alvin Reyes

Alvin has an Information Technology Degree from Mapua Institute of Technology. During his studies, he was already heavily involved in a number of small to large projects where he primarily contributes by doing programming, analysis design. After graduating, he continued to do side projects on Mobile, Desktop and Web Applications.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button