• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Spring – Dependency injection

June 9, 2011 By j2eereference 1 Comment

Dependency injection is the most basic thing that Spring does. But how dependency injection works?

We will see how Spring achieve dependency injection with a simple example. In this example will demonstrate the basics of Spring. Here the first class in the example is a service class whose purpose is to print “Welcome to j2eereference.com”. Below code is the GreetingService interface, which defines the service class.

Java
1
2
3
 public interface GreetingService {
    void sayWelcome();
  }

And GreetingServiceImpl implements the GreetingService interface. Although it’s not necessary to hide the implementation behind an interface, it’s highly recommended as a way to separate the implementation from its contract.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class GreetingServiceImpl implements GreetingService {
private String greeting;
 
public GreetingServiceImpl()
 
{}
 
public GreetingServiceImpl(String greeting)
 
{
 
this.greeting = greeting;
 
}
 
public void sayWelcome() {
 
System.out.println(greeting);
 
}
 
public void setGreeting(String greeting) {
 
this.greeting = greeting;
 
}

You may have noticed the below points in the above class

1)      The GreetingServiceImpl class has a single property: greeting. This property is simply a String that holds the message that will be printed when the sayWelcome () method is called.

2)      You may have noticed that greeting can be set in two different ways: by the constructor or by the property’s setter method.

Who will make the call to either the constructor or the  setGreeting() method to set the property ? We are going to let the Spring container to set the greeting property.

Spring configuration file

The Spring configuration file (In our example, conf.xml) tells the container how to configure the greeting service.

XHTML
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="greetingService" class="GreetingServiceImpl">
<property name="greeting" value="Welcome to j2eereference.com" />
</bean>
</beans>

The above XML declares an instance of a GreetingServiceImpl in the Spring container and configures its greeting property with a value of “Welcome to j2eereference.com”

Let’s dig into the details of this XML file a bit to understand how it works.

The <bean> element is used to tell the Spring container about a class and how it should be configured. Here, the id attribute is used to name the bean greetingService and the class attribute specifies the bean’s fully qualified class name.

Within the <bean> element, the <property> element is used to set a property, in this case the greeting property. As shown here, the <property> element tells the Spring container to call setGreeting(), passing in “Welcome to j2eereference.com” when instantiating the bean.

The following snippet of code illustrates roughly what the container does when instantiating the greeting service based on the above XML definition.

GreetingServiceImpl greetingService = new GreetingServiceImpl();

greetingService.setGreeting(“Welcome to j2eereference.com”);

Setting the constructor argument value

You can let the Spring to set the greeting property through GreetingServiceImpl’s single argument constructor. For example:

1
&lt;bean id="greetingService"

class=”GreetingServiceImpl”>

<constructor-arg value=” Welcome to j2eereference.com” />

</bean>

The following code illustrates how the container will instantiate the greeting service  when using the <constructor-arg> element:

GreetingServiceImpl greetingService =new GreetingServiceImpl(“Welcome to j2eereference.com”);

The below class- MyFirstSpringApp  that loads the Spring container and uses it to retrieve the greeting service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.springframework.beans.factory.BeanFactory;
 
import org.springframework.beans.factory.xml.XmlBeanFactory;
 
import org.springframework.core.io.FileSystemResource;
 
public class MyFirstSpringApp {
 
public static void main(String[] args) throws Exception
{
 BeanFactory factory =
 
new XmlBeanFactory(new FileSystemResource("conf.xml"));
 
GreetingService greetingService =
 
(GreetingService) factory.getBean("greetingService");
 
greetingService.sayWelcome ();
 
}
}

The BeanFactory class used here is the Spring container. After loading the conf.xml file into the container, the main() method calls the getBean() method on the BeanFactory to retrieve a reference to the greeting service. With this reference in hand, it finally calls the sayWelcome() method. When you run the MyFirstSpringApp application, it prints

Welcome to j2eereference.com

Related Posts

  • Spring JSR-250 Annotations
  • Injecting singleton class with spring
  • Writing First Aspect in spring
  • What is Aspect Oriented Programming (AOP)
  • Autowired Annotation
  • Constructor injection in spring
  • Bean autowiring
  • LifeCycle call backs in Spring
  • BeanPostProcessor in Spring
  • Initializing list of values using Spring

Filed Under: Spring

Reader Interactions

Comments

  1. satyansu says

    March 7, 2012 at 9:37 am

    Nice work indeed!

    Satyansu

    Reply

Leave a Reply Cancel reply

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

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.