Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to inject an object using Spring configuration file

In this article, we will learn about the Object injection and the process to inject an object using spring mechanism.

A class is a user defined data type, while we define an instance of that type, this instance is called object. Hence an object is a class instance that is used to access class member variables and methods. While we create an instance of a class into another defining class is called object injection.

Object injection in detail:

To access data members of a defined class, it is necessary to create an instance of this class. This instance may be created using new keyword in java. But this kind of creating an instance of a class is considered as a tight coupling of a creating instance of a class. Spring provides a way of creating an instance of a class in the way of Loose Coupling. Once a class instance has been created, this may be used within other classes. This type of object access is known as Object linking or injecting.

Spring provides a mechanism to share a created bean object into another bean. This sharing of an instance in spring framework is called injecting an object. To inject a bean into another bean, an attribute “ref” with its “name” is used inside <property> tag. The value assigned to “ref” attribute would be the bean name that is being injected into the defining bean: <property name = “property-name” ref = “bean-id-or-name”/>

Application Example:

Let’s discuss with an example that will create a web application using Spring MVC and inject one bean into another bean into the spring configuration file.

All the request hits to web.xml deployment descriptor file that transfers these requests to ServletDispatcher class defined into the “org.springframework.web.servlet” package.

Listing 1: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ObjectInjectionApp</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>ObjectInject</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ObjectInject</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

The above code loads index.jsp as default view and transfers all html file request to DispatcherServlet class.

All the requests are transferred to “ObjectInject-servlet.xml” spring configuration file that loads all the controllers defined into package “com.springmvcapp.controller” using <context:component-scan> tag.

A <bean> tag is defined to define all the views that should be loaded on specific response processed by controller against a specific request.

This tag contains three properties named:

  • “viewClass” as “org.springframework.web.servlet.view.JstlView”,
  • “prefix” as “WEB-INF/jsp”
  • “suffix” as “.jsp”

Which are defined into Listing 2

Listing 2: ObjectInject-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.springmvcapp.controller" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

The above coding defines MVC pattern for the application. It define the directory path for controller, models and view and also defines, how to manipulate controller, model and view classes.

Now, Lets define a controller class “ObjectInject”. Annotation @Controller is used to define “ObjectIntect” class as a controller class, where @RequestMapping annotation is used to define map url with the controller methods.

Listing 3: ObjectInject.java

package com.springmvcapp.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ObjectInjection {

	   @RequestMapping("/line")
       public ModelAndView line() {
    	   ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    	   Line obj = (Line) context.getBean("line");
    	   return new ModelAndView("welcome", "message1", "<div align = 'center'><h1>" + obj.draw() + "</h1></div>");
      }
}

The above code defines a ObjectInjection class of Controller type that defines a method line() that is to be mapped by the url stirng: http://localhost:8080/object_inject/line.html

The line() method defines a ApplicationContext object that creates and instance of Line class using “line” bean definition and call method draw() of Line class.

Now, Define a Line class this class creates two instance of Point class.

Listing 4: Line.java

package com.springmvcapp.controller;

public class Line {
	private Point point0;
	private Point point1;
	
		
	public Point getPoint0() {
		return point0;
	}


	public void setPoint0(Point point0) {
		this.point0 = point0;
	}


	public Point getPoint1() {
		return point1;
	}


	public void setPoint1(Point point1) {
		this.point1 = point1;
	}


	public String draw(){
		return "Points for drawn line are: (" + 
				getPoint0().getX() + "," + getPoint0().getY() +
				"), (" +
				getPoint1().getX() + "," + getPoint1().getY() +
				")";
	}
}

The above code creates a bean class “Line” that creates two instances of class Point and its getter() and setter() methods. These methods are used to access line points to draw a line. To access these points, getX() and getY() method of Point class are called.

Listing 5: Point.java

package com.springmvcapp.controller;

public class Point {
	private int x;
	private int y;
	
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
}

The above code defines a bean class “Point”. It declares two private member variables x and y and its getter() and setter() methods.

A spring configuration file “spring.xml” is defines into the classpath to define bean object of “Line” and “Point” classes.

Listing 6: spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <bean id = "line" class = "com.springmvcapp.controller.Line">
    	<property name = "point0" ref = "point0"/>
    	<property name = "point1" ref = "point1"/>
    </bean>
    <bean id = "point0" class = "com.springmvcapp.controller.Point">
    	<property name="x" value = "0"/>
    	<property name="y" value = "0"/>
    </bean>
    <bean id = "point1" class = "com.springmvcapp.controller.Point">
    	<property name="x" value = "21"/>
    	<property name="y" value = "0"/>
    </bean>
</beans>

The above code defines three bean objects by ids “line”, “point0” and “point1”. Two bean objects “point0” and “point1” assign values to their member variables using property tag as: <property name = “class-member-variable-name” value “value-assigned”/>

Ex.: <property name="x" value = "0"/>

Where bean definition for id “line” inject these bean definitions using “ref” attribute of tag as: <property name = “class-member-variable-name” ref = “bean-id-or-name”/>

Ex.: <property name = "point0" ref = "point0"/>

When an application is deployed, it loads index.jsp page.

Listing 7: index.jsp

<html>
<head>
<title>Object Injection App | Index</title>
</head>
<body>
	<br>
	<div align='center'>
	<h2>
		WELCOME TO Object Injection APP     
		<a href="line.html">Load Line Draw</a>
	</h2>
	</div>
</body>
</html>

The above code displays the welcome message and creates an anchor tag that request for line.html page to be loaded.

When line.html page is requested to server, it requests to controller “ObjectInject” to execute method “line()”. This method loads the welcome.jsp file defined in “WEB-INF/jsp” directory.

Listing 8: welcome.jsp

<html>
<head>
    <title>Object Injection App</title>
</head>
<body>
	<div align="center"><br><br><h1>Line Drawn by Object Injection</h1></div>
    ${message1}
</body>
</html>

The above code loads the welcome message as “Line Drawn by Object Injection” and also displays the message using “message1” that is processed by line() method of controller class “ObjectInject”.

Once the application has been deployed on the server, it loads index.jsp page by url: http://localhost:8080/object_inject/

As shown into the figure:

loads index.jsp page, one an application has been deployed and loaded

Figure 1: loads index.jsp page, one an application has been deployed and loaded

The above figure displays the index.jsp page by default as shown in the figure.

When a user clicks on “Load Line Draw”, it redirects the user to url: http://localhost:8080/object_inject/line.html

As shown into the figure:

loads welcome.jsp page on request of line.html page.

Figure 2: loads welcome.jsp page on request of line.html page.

The above url request loads welcome.jsp page, once user requests for line.html page. This request hits line() method of “ObjectInject” controller that redirects the response to welcome.jsp page and displays the message processed from line method with the string processed by welcome.jsp page.

Required Tools and application:

To create and run his application, we are required following tools and application:

  • Eclipse IDE (Ex. Juno)
  • JDK Environment (Ex. JDK 7)
  • Web or Application Server (Ex. Tomcat Apache Web Server 7)

Required Jar Files:

To run this application we are required a set of jar files as shown into the figure 4:

Required Jar file to run above example

Figure 3: Required Jar file to run above example

The above figure shows the list of jar files required by Spring framework to run web application based on Spring Framework.

Directory Structure Created:

Directory Structure created by Eclipse IDE

Figure 4: Directory Structure created by Eclipse IDE

The above figure shows the directory structure created by Eclipse IDE that creates a web application managed by Spring MVC framework.

Conclusion:

In this article, we learn:

  • What is Object injection?
  • How do we inject an object using spring mechanism?


Have more than 5 years experience about Java, .Net, C and C++.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login