Wednesday, 13 May 2015

Spring constructor injection

In this post, i am going to explain, how to create beans using constructor injection.

Step 1 : Create new maven project “spring_tuorial”. Project structure looks like below.


Step 2 : Update “pom.xml” file for maven dependencies.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
 <modelVersion>4.0.0</modelVersion> 
 <groupId>spring_tutorial</groupId> 
 <artifactId>spring_tutorial</artifactId> 
 <version>0.0.1-SNAPSHOT</version> 
 <packaging>war</packaging> 
 <name>spring_tutorial</name> 
 <description>spring_tutorial</description> 
 <properties> 
  <org.springframework-version>4.1.5.RELEASE</org.springframework-version> 
 </properties> 

 <dependencies> 
  <dependency> 
   <groupId>org.springframework</groupId> 
   <artifactId>spring-context</artifactId> 
   <version>${org.springframework-version}</version> 
  </dependency> 

 </dependencies> 
</project>

Step 3: Create new package “com.springtutorial.model” under “src/main/java”.


Step 4: Create “Employee” class under the package “com.springtutorial.model”.
package com.springtutorial.model; 

public class Employee { 
  private String firstName; 
  private String lastName; 
  private int id; 

  public Employee() { 

  } 

  public Employee(int id, String firstName) { 
    this.id = id; 
    this.firstName = firstName; 
  } 
 
  public Employee(String firstName, String lastName) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
  } 

  public String getFirstName() { 
    return firstName; 
  } 

  public void setFirstName(String firstName) { 
    this.firstName = firstName; 
  } 

  public String getLastName() { 
    return lastName; 
  } 

  public void setLastName(String lastName) { 
    this.lastName = lastName; 
  } 

  public int getId() { 
    return id; 
  } 

  public void setId(int id) { 
    this.id = id; 
  } 

  @Override 
  public String toString() { 
    StringBuilder builder = new StringBuilder(); 
    builder.append("Employee [firstName=").append(firstName).append(", lastName=").append(lastName) 
        .append(", id=").append(id).append("]"); 
    return builder.toString(); 
  } 

} 

Step 5 : Create “spring.xml” file in “src/main/resources”.
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" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

 <bean id="employee1" class="com.springtutorial.model.Employee" /> 

 <bean id="employee2" class="com.springtutorial.model.Employee"> 
  <constructor-arg type="int" value="553" /> 
  <constructor-arg type="java.lang.String" value="Hari Krishna" /> 
 </bean> 


 <bean id="employee3" class="com.springtutorial.model.Employee"> 
  <constructor-arg type="java.lang.String" value="Hari Krishna" /> 
  <constructor-arg type="java.lang.String" value="Gurram" /> 
 </bean> 


</beans>

"spring.xml" is used to assign unique IDs to different beans, to control the creation of objects with different values.
        
<bean id="employee1" class="com.springtutorial.model.Employee" />
Above statement  initialize Employee class using default constructor.

<bean id="employee2" class="com.springtutorial.model.Employee">
         <constructor-arg type="int" value="553" />
         <constructor-arg type="java.lang.String" value="Hari Krishna" />
</bean>
Above statement  initialize Employee class using constructor “public Employee(int id, String firstName)”.

<bean id="employee3" class="com.springtutorial.model.Employee">
         <constructor-arg type="java.lang.String" value="Hari Krishna" />
         <constructor-arg type="java.lang.String" value="Gurram" />
</bean>
Above statement  initialize Employee class using constructor public Employee(String firstName, String lastName)”.

You have to make sure that “spring.xml” file is available in CLASSPATH and use the same name in main application while creating application context as shown in Main.java file.

Step 6 : Create package “com.springtutorial.main” under “src/main/java”.


Step 7 : Create Main class under package “com.springtutorial.main”.
package com.springtutorial.main; 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 

import com.springtutorial.model.Employee; 

public class Main { 
  public static void main(String args[]) { 
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); 

    Employee emp1 = (Employee) context.getBean("employee1"); 
    Employee emp2 = (Employee) context.getBean("employee2"); 
    Employee emp3 = (Employee) context.getBean("employee3"); 
    
    System.out.println(emp1); 
    System.out.println(emp2); 
    System.out.println(emp3); 
  } 
} 


Step 8 : Run Main.java,you will get output like below.
Mar 22, 2015 8:49:42 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@12e99be: startup date [Sun Mar 22 20:49:42 IST 2015]; root of context hierarchy 
Mar 22, 2015 8:49:42 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 
INFO: Loading XML bean definitions from class path resource [spring.xml] 
Employee [firstName=null, lastName=null, id=0] 
Employee [firstName=Hari Krishna, lastName=null, id=553] 
Employee [firstName=Hari Krishna, lastName=Gurram, id=0] 

Final project structure looks like below.





Prevoius                                                 Next                                                 Home

Struts2 : Preparable Interface

Struts2 provide Preparable interface, Any action class which implements Preparable interface, overrides the prepare method.

public interface Preparable {

    /**
     * This method is called to allow the action to prepare itself.
     *
     * @throws Exception thrown if a system level exception occurs.
     */
    void prepare() throws Exception;
   
}

Prepare interceptor calls prepare() on actions which implement Preparable. "prepare()" method called before the actual execute method runs.

Following example creates a registration form, with fields username, password, mailId, country, hobbies. The data for the hobbies, country is updated using the prepare method of the action class.

Step 1: Create new maven project “struts_tutorial”. Follow first 3 steps from the following link to make the project setup.


Step 2: create struts.xml. Since Struts 2 requires struts.xml to be present in classes folder. So create struts.xml file under the WebContent/WEB-INF/classes folder. Eclipse does not create the "classes" folder by default, so you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder.

struts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <package name="default" extends="struts-default">
  <action name="getRegistration" class="learn.struts.GetRegistrationForm">
   <result name="success">/register.jsp</result>
  </action>
 </package>
</struts>

Step 3: Create register.jsp with following data.

register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Registration Form</title>
<s:head />
</head>
<body>
 <s:form name="registerform" action="registerUser">
  <s:textfield name="username" label="User Name" required="true" />
  <s:password name="password" label="Password" required="true" />
  <s:textfield name="email" label="Email Id" required="true" />

  <s:checkboxlist label="hobbies" list="hobbies" name="hobbies">
  </s:checkboxlist>
  
  <s:select list="country" label="Country" name="country"></s:select>
  <s:submit />
 </s:form>
</body>
</html>


Step 4: Create action class GetRegistrationForm.java, inside the package “learn.struts”.

package learn.struts;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.Preparable;

public class GetRegistrationForm implements Preparable {
 private List<String> hobbies;
 private List<String> country;

 public List<String> getCountry() {
  return country;
 }

 public List<String> getHobbies() {
  return hobbies;
 }

 public String execute() {
  return "success";
 }

 @Override
 public void prepare() throws Exception {
  hobbies = new ArrayList<>();
  hobbies.add("Mobiles");
  hobbies.add("Game Consoles");
  hobbies.add("Laptops");
  hobbies.add("Portable Music Players");

  country = new ArrayList<>();
  country.add("India");
  country.add("Nepal");
  country.add("Japan");
  country.add("Sri Lanka");

 }
}
Run the Application and hit following URL. 

You will get following jsp page. Observe the jsp file, it contains the country and hobbies data, which I set in prepare method of action class.


Complete project structure looks like following.





Prevoius                                                 Next                                                 Home