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 Use Constructor Injection in Spring with Beans

In this article, we will learn about the constructor injection and why do we use this. Also we will see the process to use constructor injection in Spring to initialize constructors of a bean class.

Constructors are used to initialize class variables. The constructor is defined as method that doesn’t return any values explicitly and defined as method that has method name as class name. A constructor may be overloaded as method overloading. If we define constructor, then it is our responsibility to declare all the type of constructor from its initial level like default constructor, parameterized constructor.

Constructor Injection in Details:

We may have any number of constructors in our bean classes. A Spring constructor injection is a way to initialize these defined constructors using Spring Bean Factory mechanism. It is defined Spring configuration file using xml tags or using annotation into the bean class definition. We shall use constructor injection using xml file configuration.

A constructor injection is defined in <constructor-arg> tag using its attribute “value” as: <constructor-arg value = “desired-value”/>

Spring framework understands the type of assigned value to the constructor and finds the type of constructor to be initialized automatically, whether a default or parameterized and what kind of parameterized constructor should be initialized. It also converts the initialized value to its constructor type automatically.

In this article we’ll have an example that will be based on Spring MVC framework and will use ApplicationContext to initialize bean classes.

Required Tools and Application:

We are required following listed tools and applications:

  • Eclipse IDE (Eclipse Juno)
  • JDK Environment (JDK7)
  • Application Server (Tomcat Apache 7)

To see more about our Spring articles, please refer to this link!!

Required Jar Files:

The following figure list all the required jar files

Listing all the required Spring Jar files for this example

Figure 1: Listing all the required Spring Jar files for this example

This figure shows all the required Spring mvc jar files to support Spring mvc application.

Example Coding:

Now, let’s have a look on example coding that will be initializing bean class constructor using Spring mvc framework. This application will be initialized class variables to triangle name and will be displayed into the web page.

All the request hits on the server, are managed by deployment descriptor defined in web.xml

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>ConstructorInjection</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>ConstructorInjectionApp</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ConstructorInjectionApp</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

This descriptor transfers all the requests to DispatcherServlet that looks for ContructorInjectionApp-servlet.xml file to configure controller and its methods with the relevant defined views. This class defined in “org.springframework.web.servlet” package. It loads the default jsp file “index.jsp” as view.

Listing 2: ContructorInjectionApp-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 code defines tag that loads the defined package. The next line defines a tag with id name “viewResolver” for class “UrlBasedViewResolver” defined in “org.springframework.web.servlet.view” package with its properties named “viewClass” for value “org.springframework.web.servlet.viewJstlView” and named “prefix” with value “/WEB-ING/jsp/” and named “suffix” with its value “.jsp”.

The next listing defines the index.jsp file coding.

Listing 3: index.jsp

<html>
<head>
<title>Constructor Injection App | Index</title>
</head>
<body>
	<br>
	<div align='center'>
	<h2>
		WELCOME TO Constructor Injection APP     
		<a href="triangle.html">Load Triangle</a>
	</h2>
	</div>
</body>
</html>

In the above code, a welcome message is displayed with an anchor tag for “triangle.html” url.

There is one jsp file defined in directory “WEB-INF/jsp/” that is loaded for response according to submitted url request with the updated response from controller.

Listing 4: welcome.jsp

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

The above code displays the response message from controller, while a request is generated for “triangle()” method of “HelloWorld” controller. To access the variables defined in controller class as: ${controller-member-variable-name}

Ex: ${message}

Now, Let’s define a controller “HelloWorld” as:

Listing 5: HelloWorld.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 HelloWorld {

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

The above code defines a class “HelloWorld” as a controller. @Controller annotation is used to define a controller. This annotation class is defined in “org.springframework.stereotype.Controller” class. To map a url request to controller class method, we use @RequestMapping annotation of “org.springframework.web.bind.annotation.RequestMapping” class. “/triangle” is passed as parameter to @RequestMapping annotation definition that should be defined before method definition. A method triangle() is defined of return type “ModelAndView” class type. A ModelAndView type constructor accepts three parameters of String type.

We define ApplicationContext object that contain bean definition from “spring.xml” file and call a draw() method of “Triangle” class using “triangle” bean defined in “spring.xml” file.

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 = "triangle" class = "com.springmvcapp.controller.Triangle">
    	<constructor-arg value="Equiletral Type"/>
    </bean>
</beans>

The above code defines a by id as “triangle” for class “com.springapp.controller.Triangle” that defines a constructor type as: <constructor-arg value= “Equiletral Type”/>

Listing 7: Triangle.java

package com.springmvcapp.controller;

public class Triangle {
	private String type;
	
	public Triangle(String type){
		this.type = type;
	}
	
	public String getType() {
		return type;
	}

	public String draw(){
		return getType() + " Triangle Drawn";
	}
}

The above code defines a bean class with one parameterized constructor that accept a String variable, defining triangle type and a draw() method that returns String by calling getType() method with string tag.

Directory Structure for Application:

Directory Structure created for application using Eclipse IDE

Figure 2: Directory Structure created for application using Eclipse IDE

The above figure shows the directory structure for the web application created using Eclipse IDE.

Once we have deployed this application on the web server, the default page index.jsp is loaded into the web browser as:

index.jsp page loaded by default, once application is deployed on the server

Figure 3: index.jsp page loaded by default, once application is deployed on the server http://localhost:8080/app_context/

The above figure displays the default page loaded into the web browser. Once user hits the “Load Triangle” anchor tag. It loads triangle.html page as shown into the next figure.

triangle.html page loaded, while click on the “Load Triangle” by controller

Figure 4: triangle.html page loaded, while click on the “Load Triangle” by controller

A triangle() method is called of HelloWorld class, while a url: http://localhost:8080/app_context/triangle.html is visited.

Conclusion:

In this article, we learn:

  • What is constructor injection and why do we use this?
  • How do we use constructor injection in Spring to initialize constructors of a bean class?


Web developer and passioned for web design, SEO and front end technologies.

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