Builder design pattern allows to create complex object step by step and also enforces a process to create an object as a finished product.Construction of object should be such that same construction process can create different representations.Director controls the construction of object and only director knows what type of object to create.

For example, You can consider printing of a book.Printing of a book involves various steps such as printing table of content,preface,introduction,chapters and conclusion.Finally you will get complete book object. With the help of same above process,you can print books with different properties.
 
As described by Gof:
"Separate the construction of a complex object from its representation so that the same construction process can create different representations"

Generic UML diagram for builder design pattern:

Elements:

  • Builder
    • specifies an abstract interface for creating parts of a product object.
  • ConcreteBuilder
    • constructs and assembles parts of the product by implementing the builder interface.
    • defines and keeps track of the representation it creates.
    • provides an interface for retrieving the product.
  • Director
    • constructs an object using builder interface.
  • Product
    • represents the complex object under construction.ConcreteBuilder builds the product's internal representation and defines the process by which it is assembled.
    • includes classes that define the constituent parts,including interfaces for the assembling the parts into final result.

When to use it:

  • Object creation algorithms should be independent of system.
  • New creation algorithm can be added without changing core code.
  • The construction process must allow different representations for the object that' s contructed.
  • Runtime control over creation process is required.

WorkFlow:

  • The client creates the director object and configures it with the desired builder object.
  • Director notifies builder whenever a part of product should be built.
  • Builder handles requests from the director and adds parts to the product.
  • The clients retrieves the product from builder.

Example:

You can consider priniting of a book.Printing of a book involves various steps such as printing table of content,preface,introduction,chapters and conclusion.Finally you will get complete book object. With the help of same above process,you can write books with different properties.  BookWriter will instruct bookBuilder to print book in steps and return final book object.

Comparing to generic UML diagram of builder pattern:
  • BookBuilder(Builder)
  • TechnicalBookBuilder(ConcreteBuilder)
  • FictionalBookBuilder(ConcreteBuilder)
  • BookWriter(Director)
  • Book(Product)
Java codes for above classes:
Following class is our product class.Object of this class will be returned by builder.

Book.java (Product):
package org.arpit.javapostsforlearning.designpatterns;

public class Book {

 String introduction;
 String tableOfContent;
 String preface;
 String chapters;
 String glossary;
  
 public void setIntroduction(String introduction) {
  this.introduction = introduction;
 }
 public void setTableOfContent(String tableOfContent) {
  this.tableOfContent = tableOfContent;
 }
 public void setPreface(String preface) {
  this.preface = preface;
 }
 public void setChapters(String chapters) {
  this.chapters = chapters;
 }
 public void setGlossary(String glossary) {
  this.glossary = glossary;
 }
}
Following interface is our builder interface.Builder interface provides steps or process.Here we have five steps-buidTableOfContent,buildPreface,buildIntroduction,buildChapters,buildGlossary.It also has method to return book(product) object. 
BookBuilder.java (Builder):
package org.arpit.javapostsforlearning.designpatterns;

public interface BookBuilder {

        public void buildTableOfContent();
        public void buildPreface();
        public void buildIntroduction();
        public void buildChapters();
        public void buildGlossary();
        public Book getBook();
}
Following class is our first implementation of builder interface.We are having multiple concrete builder class to support  same construction process creating multiple representations.

TechnicalBookBuilder.java(ConcreteBuilder):
package org.arpit.javapostsforlearning.designpatterns;

public class TechnicalBookBuilder implements BookBuilder{
 private Book book;

 public TechnicalBookBuilder()
 {
  book=new Book();
 }
 public void buildTableOfContent() {
  System.out.println("printing technical table of content");
  book.setTableOfContent("technical table of content");
 }
 
 public void buildPreface() {
  System.out.println("printing preface");
  book.setTableOfContent("preface");
 }
 public void buildIntroduction() {
  System.out.println("printing technical introduction");
  book.setTableOfContent("technical introduction");
 }

 public void buildChapters() {
  System.out.println("printing technical chapters");
  book.setChapters("technical chapters");
 }

 public void buildGlossary() {
  System.out.println("printing technical glossary");
  book.setGlossary("Technical glossary");
 }

 public Book getBook() {
  return book;
 }
}

Following class is our second implementation of builder interface.

FictionalBookBuilder.java(ConcreteBuilder):
package org.arpit.javapostsforlearning.designpatterns;

public class FictionalBookBuilder implements BookBuilder{
 private Book book;

 public FictionalBookBuilder()
 {
  book=new Book();
 }
 public void buildTableOfContent() {
  System.out.println("printing fictional table of content");
  book.setTableOfContent("fictional table of content");
 }
 
 public void buildPreface(){
  System.out.println("printing preface");
  book.setTableOfContent("preface");
 }
 public void buildIntroduction() {
  System.out.println("printing fictional introduction");
  book.setTableOfContent("fictional introduction");
 }

 public void buildChapters() {
  System.out.println("printing fictional chapters");
  book.setChapters("fictional chapters");
 }

 public void buildGlossary() {
  System.out.println("printing fictional glossary");
  book.setGlossary("Fictional glossary");
 }

 public Book getBook() {
  return book;
 }

}

Following class is our director class which will instructs BookBuilder to print parts of book and return final book object
BookWriter.java(Director):
package org.arpit.javapostsforlearning.designpatterns;
public class BookWriter {

 BookBuilder bookBuilder;
 
 public BookWriter(BookBuilder bookBuilder) {
  super();
  this.bookBuilder = bookBuilder;
 }

 public Book getBook()
 {
  return this.bookBuilder.getBook();
 }
 
 public void printBook()
 {
  this.bookBuilder.buildTableOfContent();
  this.bookBuilder.buildPreface();
  this.bookBuilder.buildIntroduction();
  this.bookBuilder.buildChapters();
  this.bookBuilder.buildGlossary();
 }
}
BuilderDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;
public class BuilderDesignPatternMain {
 
 
 public static void main(String[] args) {
  
  System.out.println(Printing technical book:");
  BookBuilder technialbookBuilder=new TechnicalBookBuilder();
  BookWriter technicalBookWriter=new BookWriter(technialbookBuilder);
  technicalBookWriter.printBook();
  Book technicalbook=technicalBookWriter.getBook();
  System.out.println("Technical Book Printed:"+technicalbook);
  System.out.println("******************************************");
  System.out.println(Printing fictional book:");
  BookBuilder fictionalbookBuilder=new FictionalBookBuilder();
  BookWriter fictionalBookWriter=new BookWriter(fictionalbookBuilder);
  fictionalBookWriter.printBook();
  Book fictionalbook=fictionalBookWriter.getBook();
  System.out.println("Fictionalbook book printed:"+fictionalbook);
 }
} 
For printing technical book,we have configured bookWriter object with technicalBookBuilder.BookWriter instructed to technicalbookbuilder to print book and return final book object.Same is true for fictional book.So with help of same construction process,we have printed two kinds of book.i.e. technical and fictional.
Output:
Printing technical book:
printing technical table of content
printing preface
printing technical introduction
printing technical chapters
printing technical glossary
Technical Book printed:org.arpit.javapostsforlearning.designpatterns.Book@1888759
******************************************
Printing fictional book:
printing fictional table of content
printing preface
printing fictional introduction
printing fictional chapters
printing fictional glossary
Fictionalbook book printed:org.arpit.javapostsforlearning.designpatterns.Book@1f1fba0 

References:The Gang of Four (GoF) book

Proxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object's code.

As described by GoF:
"Provide a surrogate or placeholder for another object to control access over it."

Real life example may be proxy server used in IT companies for internet access.It blocks access to social networking sites like facebook,twitter and other contents which are not work related.

When to use it:

Proxy is required whenever there is need for more sophisticated or versatile reference to an object than a simple pointer.Here are some situations when proxy pattern is applicable.
  1. A remote proxy provides a local representative for an object in a different address space.Providing interface for remote resources such as web service or REST resources.
  2. A virtual proxy creates expensive object on demand.
  3. A protection proxy controls access to the original object.Protection proxies are useful when objects should have different access rights.
  4. A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.
  5. Adding a thread-safe feature to an existing class without changing the existing class's code. 

UML diagram for proxy design pattern:

Elements:

  • Proxy
    • maintains a reference that lets the proxy access the real subject.Proxy may refer to a subject if the RealSubject and Subject interface are the same.
    • provides an interface identical to Subject's so that proxy can be substituted for the real subject.
    • controls access to the real subject and may be responsible for creating and deleting it.
  • Subject
    • defines the common interface for RealSubject and proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubject
    • defines the real object that proxy represents. 

WorkFlow:

Proxy forwards request to RealSubject when appropriate ,depending on the kind of proxy.

Example: 

Let's see an example.I am taking example of protection proxy. In our example, we have a folder in which you can perform various operation such as copy,paste file or subfolder.In OOP terms,we have IFolder interface and Folder class which provides performOperatons() method, and these are the existing class and interface that we cannot change. We want to further specify that only user with authorization can access it and perform operations such as cut or copy files and sub folder.

UML diagram for example:

Comparing with above generic elements,we have
  • FolderProxy(Proxy)
  • Folder(RealSubject)
  • IFolder(Subject)
Java codes for above classes:

IFolder.java (Subject):
package org.arpit.javapostsforlearning.designpatterns;

public interface IFolder {

    public void performOperations();
}
Following class is our realSubject class.Lets say we can not change it but we want to provide authorization on it.
Folder.java (RealSubject):
package org.arpit.javapostsforlearning.designpatterns;

public class Folder implements IFolder{
 
 public void performOperations()
 {
       // access folder and perform various operations like copy or cut files
  System.out.println("Performing operation on folder");
 }

}
Following class provides authorization to Folder class.It checks for userName and password and if matched then only it gives access to folder.
FolderProxy.java(Proxy):
package org.arpit.javapostsforlearning.designpatterns;

public class FolderProxy implements IFolder{

 Folder folder;
 User user;
  
 public FolderProxy(User user) {
  this.user = user;
 }


 public void performOperations() {
  
  if(user.getUserName().equalsIgnoreCase("arpit") && user.getPassword().equalsIgnoreCase("arpit"))
  {
   folder=new Folder();
   folder.performOperations();
  }
  else
  {
   System.out.println("You don't have access to this folder");
  }
      }
} 
User.java:
package org.arpit.javapostsforlearning.designpatterns;

public class User {

 String userName;
 String password;
  
 public User(String userName, String password) {
  this.userName = userName;
  this.password = password;
 }
 
 public String getUserName() {
  return userName;
 }
 public String getPassword() {
  return password;
 }
 
}
ProxyDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;

public class ProxyDesignPatternMain {

 public static void main(String[] args) {
  
  //When you click on folder,Lets say a GUI form will ask for userName and password.
  //and this GUI will create this user object
  
  // If we give correct userName and password
  User user=new User("arpit","arpit");
  FolderProxy folderProxy=new FolderProxy(user);
  System.out.println("When userName and password are correct:");
  folderProxy.performOperations();
  System.out.println("**************************************");
  // if we give wrong userName and Password
  User userWrong=new User("abc","abc");
  FolderProxy folderProxyWrong=new FolderProxy(userWrong);
  System.out.println("When userName and password are incorrect:");
  folderProxyWrong.performOperations();
 }

}
Output:
When userName and password are correct:
Performing operation on folder
**************************************
When userName and password are incorrect:
You don't have access to this folder

So without changing Folder class,we have provide authentication to folder with the help of FolderProxy class.

Source code:

Source:Download 

Composite design patten allows you to have a tree structure and ask each node in the tree structure to perform a task.You can take real life example of a organization.It have general managers and under general managers, there can be managers and  under managers there can be developers.Now you can set a tree structure and ask each node to perform common operation like getSalary().

As described by Gof:
"Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly".

Composite design pattern treats each node in two ways-Composite or leaf.Composite means it can have other objects below it.leaf means it has no objects below it.

Tree structure:


When to use it:

  • you want to represent part-whole hierachies of objects.
  • you want client to be able to ignore difference between compositions of objects and individual objects.Clients will treat all objects in the composite structure uniformly.

UML Diagram for Composite design pattern:

Elements:

  • Component
    • declares interface for objects in composition.
    • implements deafault behaviour for the interface common to all classes as appropriate.
    • declares an interface for accessing and managing its child components.
  • Leaf
    • represents leaf objects in the composition.A leaf has no children.
    • defines behaviour for primitive objects in the composition.
  • Composite
    • defines behaviour for components having children.
    • stores child components.
    • implements child related operations in the component interface.
  • Client
    • manipulates objects in the composition through the component interface.

WorkFlow:

Client use the component class interface to interact with objects in the composition structure.if recipient is a leaf then request is handled directly.If recipient is a composite,then it usually forwards request to its child components,possibly performing additional operations before and after forwarding.

Recursion:

What makes the Composite pattern one of the most beautiful is the power of recursion. I can explain this with the same organization example. You want to find the total salary paid to all employees of the organization. It is nothing but the salary of CEO + the salary paid to all the departments. What is the salary of a department? It is the salary of the department head + the salary of all projects. What is the total salary of a project? It is the salary of the project manager + the salary of all the project members. In short, the salary of anything is the salary of self + the salary of all its sub groups.

Example:

In a small organization,there are 5 employees.At top position,there is 1 general manager.Under general manager,there are two employees,one is manager and other is developer and further manager has two developers working under him.We want to print name and salary of all employees from top to bottom.

Tree structure for example:

UML diagram for above example:


Comparing from above generic elements.Our example consist of following elements.
  • Manager(Composite)
  • Developer(Leaf)
  • Employee(Component)

Java code for all above classes:

First we will create component inrteface.It represents object in composition .It has all common operation that will be applicable to both manager and developer.
Employee.java(Component) :

package org.arpit.javapostsforlearning.designpatterns;

public interface Employee {

     public void add(Employee employee);
     public void remove(Employee employee);
     public Employee getChild(int i);
     public String getName();
     public double getSalary();
     public void print();
}
Now we will create manager(composite class).Key point here is that all common method delegates its operations to child objects.It has method to access and modify its children.
Manager.java(Composite):

package org.arpit.javapostsforlearning.designpatterns;

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

public class Manager implements Employee{

 private String name;
 private double salary;

 public Manager(String name,double salary){
  this.name = name;
  this.salary = salary;
 }
 
 List<Employee> employees = new ArrayList<Employee>();
 public void add(Employee employee) {
    employees.add(employee);
 }

 public Employee getChild(int i) {
  return employees.get(i);
 }

 public String getName() {
  return name;
 }

 public double getSalary() {
  return salary;
 }

 public void print() {
  System.out.println("-------------");
  System.out.println("Name ="+getName());
  System.out.println("Salary ="+getSalary());
  System.out.println("-------------");
  
  Iterator<Employee> employeeIterator = employees.iterator();
    while(employeeIterator.hasNext()){
     Employee employee = employeeIterator.next();
     employee.print();
    }
 }

 public void remove(Employee employee) {
  employees.remove(employee);
 }

}

We will create developer class.This class is leaf node so all operations related to accessing children will be empty as it has no children.
Developer.java(Leaf):
package org.arpit.javapostsforlearning.designpatterns;
/**
 * In this class,there are many methods which are not applicable to developer because
 * it is a leaf node.
 */

public class Developer implements Employee{

    private String name;
    private double salary;

    public Developer(String name,double salary){
        this.name = name;
        this.salary = salary;
    }
    public void add(Employee employee) {
        //this is leaf node so this method is not applicable to this class.
    }

    public Employee getChild(int i) {
        //this is leaf node so this method is not applicable to this class.
        return null;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void print() {
        System.out.println("-------------");
        System.out.println("Name ="+getName());
        System.out.println("Salary ="+getSalary());
        System.out.println("-------------");
    }

    public void remove(Employee employee) {
        //this is leaf node so this method is not applicable to this class.
    }

}

CompositeDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;

public class CompositeDesignPatternMain {

 public static void main(String[] args) {
  Employee emp1=new Developer("John", 10000);
  Employee emp2=new Developer("David", 15000);
  Employee manager1=new Manager("Daniel",25000);
  manager1.add(emp1);
  manager1.add(emp2);
  Employee emp3=new Developer("Michael", 20000);
  Manager generalManager=new Manager("Mark", 50000);
  generalManager.add(emp3);
  generalManager.add(manager1);
  generalManager.print();
 }
}

Output:
-------------
Name =Mark
Salary =50000.0
-------------
-------------
Name =Michael
Salary =20000.0
-------------
-------------
Name =Daniel
Salary =25000.0
-------------
-------------
Name =John
Salary =10000.0
-------------
-------------
Name =David
Salary =15000.0
-------------

Disadvantages:

  • Once tree structure is defined,comosite design makes tree overly general.
  • Leaf class have to create some methods which has to empty.

Usage in JDK:

  • java.util.Map#putAll(Map)
  • java.util.List#addAll(Collection)
  • java.util.Set#addAll(Collection)
  • java.nio.ByteBuffer#put(ByteBuffer) (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
  • java.awt.Container#add(Component) 

Real life example:

A very simple example is using phone charger. Suppose your mobile phone needs 9 Volts of supply to get charged but main supply is 220 V which is not what you require but it can be a source and you can have something that can get 9 V out of this 220 V and supply to your phone for charging.
Now phone charger is acting as an adapter for you.  So Basically it is making a relationship between two unrelated interfaces. This  is how Adpater pattern works.

Intent:

As described by Gof:
"Convert the interface of class into another interface clients expect.Adapter lets class work together that couldn't otherwise because of incompatible interfaces".

Also known as:

Wrapper

UML diagram of generic adapter design pattern:

Elements:

  • Target
    • defines domains-specific interface client uses.
  • Client
    • collaborates with objects conforming to target interface.
  • Adaptee
    • defines existing interface that needs adapting
  • Adapter 
    • adapts the interface of adaptee to target interface. 

WorkFlow:

Clients call operations on the adapter instance.In turn adapter calls adaptee operations that carry out the request.

When to use it:

  • You want to use existing class and its interface does not match the one you need.
  • You want to create a resuable class that cooperates with unrelated or unforeseen classes that is, class that don't necessarily have compatible interfaces.

Example:

UML Diagram for example:
Comparing to above generic description of adapter pattern.
My example includes following elements:
  • PrintableList(Target)
  • PrintString(Adaptee)
  • PrintableListAdapter(Adapter)

Java code for all above classes:

Consider that we have a third party library that provides print string functionality through PrintString class.
This is our Adaptee. I know this is silly assumpsion but lets go with it for now.

PrintString.java(Adaptee) :
package org.arpit.javapostsforlearning.designpatterns;

public class PrintString {

 public void print(String s)
 {
  System.out.println(s);
 }
}

Client deals with ArrayList<String> but not with string.We have provided a PrintableList interface that expects the client input.This is our target.

PrintableList.java(Target):
package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;

public interface PrintableList {
 void printList(ArrayList<String> list);
}
Lets assume we can not change it now.
Finally we have PrintableListAdapter class which will implement PrintableList interface and will deal with our adaptee class.
PrintableListAdapter.java(Adapter):
package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;

public class PrintableListAdapter implements PrintableList{

 public void printList(ArrayList<String> list) {
 
  //Converting ArrayList<String> to String so that we can pass String to
  // adaptee class
  String listString = "";

  for (String s : list)
  {
      listString += s + "\t";
  }
  
  // instantiating adaptee class
  PrintString printString=new PrintString();
  ps.print(listString);
 }
}

AdapterDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;
public class AdapterDesignPatternMain {
 
 public static void main(String[] args)
 {
  ArrayList<String> list=new  ArrayList<String>();
  list.add("one");
  list.add("two");
  list.add("three");
  PrintableList pl=new PrintableListAdapter();
  pl.printList(list);
  
 }
}

Output:

one two three

As stated by Gof:
"Decouple an abstraction from its implementation so that the two can vary independently".

When there are inheritance hierarchies in both interface and implementation then you loose coupling because of interdependence.In other words,Decoupling interface from implementation and hiding implementation detail of abstraction from client is main objectives of bridge design pattern.

Also known as:

Handle/Body

UML diagram of generic bridge design pattern:

Elements:

  • Abstraction
    • defines the abstraction' s interface.
    • maintain reference to object of type implementor.
  • RefinedAbstraction
    • extends the interface defined by abstraction.
  • Implementor
    • defines the interface for implementation classes.This interface doesn't have to correspond exactly to abstraction's interface;in fact the two interfaces can be quite different.Typically the implementor interface provides only primitive operations,and abstraction defines higher-level operations based on these primitives.
  • ConcreteImplementor
    • implements the implementor interface and defines its concrete implementation.

When to use it:

  • Abstraction and implementation should be bound at compile time.
  • Both abstraction and implementation can have different hierarchies independently.You want to extend both hierarchies by subclassing.
  • Changes in implementation should have no impact on abstraction.
  • If you want to hide implementation of abstraction from client.
  • Best use when you have multiple implementation.

WorkFlow:

Abstaction forwards client request to its implementor object.

Example:

Before Applying bridge design pattern:

After applying bridge design pattern:

UML diagram for example:


Comparing to above generic description of bridge pattern.
My example includes following elements:
  • Shape(Abstraction)
  • Rectangle(RefinedAbstraction)
  • Circle(RefinedAbstraction)
  • Color(Implementor)
  • RedColor(ConcreteImplementor)
  • BlueColor(ConcreteImplementor)

 Java code for all above classes:

We have two inheritance hierarchies here.i.e Shape and Color.Now with help of bridge design pattern both can vary independently.

This is our abstraction class.
 Shape.java(Abstraction):

package org.arpit.javapostsforlearning.designpatterns;

abstract class Shape {
    
    Color color;
    Shape(Color color)
    {
        this.color=color;
    }
    abstract public void colorIt();
}

Rectangle.java(RefinedAbstraction):

package org.arpit.javapostsforlearning.designpatterns;

public class Rectangle extends Shape{

 Rectangle(Color color) {
  super(color);
 }

 public void colorIt() {
  System.out.print("Rectangle filled with ");
  color.fillColor();
 }
}

Circle.java(RefinedAbstraction):

package org.arpit.javapostsforlearning.designpatterns;

public class Circle extends Shape{

 Circle(Color color) {
  super(color);
 }

 public void colorIt() {
  System.out.print("Circle filled with ");
  color.fillColor();
 }
}

This is our implementor class.
Color.java(Implementor):

package org.arpit.javapostsforlearning.designpatterns;

public interface Color {

 public void fillColor();
}
RedColor.java(ConcreteImplementor):
package org.arpit.javapostsforlearning.designpatterns;

public class RedColor implements Color{

 public void fillColor() {
  System.out.println("red color");
 }
}
BlueColor.java(ConcreteImplementor):
package org.arpit.javapostsforlearning.designpatterns;

public class BlueColor implements Color{

 public void fillColor() {
  System.out.println("blue color");
 }
}
BridgeDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;

public class BridgeDesignPatternMain {

 public static void main(String[] args) {
  
  Shape s1=new Rectangle(new RedColor());
  s1.colorIt();
  Shape s2=new Circle(new BlueColor());
  s2.colorIt();
 }
}

 Output:

Rectangle filled with red color
Circle filled with blue color

Related patterns:

An Abstract Factory can create and configure a particular bridge.

The Adapter design pattern convert interface of a class ito another interface clients expects.It is usually applied to system after they are designed.Bridge on other hand is used up-front in a design to let abstractions and implementation vary independently.

This is 8 of 8 part of struts 2 tutorial.

Tutorial Content:

    Introduction to struts 2 configuring struts 2 in eclipse Struts 2 hello world example Login page with validation in struts 2 Struts 2 interceptors with example File upload in struts 2 Struts 2 ajax example Struts 2 spring 3 integration example
In this post,you will see how to integrate Spring 3 and Struts 2. Now first question comes here ,why you want to integrate spring with struts 2? Spring provides some features which are not available in struts 2.Most powerful among them is dependency injection.To learn more about dependency injection,you can refer dependency injection in spring link.

Create project named "Struts2Spring3IntegrationExample".
First of all, you need to copy following files to WEB-INF/lib and add them to project's build path. You can download and install latest version of Spring Framework from http://www.springsource.org/download
  • org.springframework.asm-3.1.1.RELEASE
  • org.springframework.beans-3.1.1.RELEASE
  • org.springframework.context-3.1.1.RELEASE
  • org.springframework.core-3.1.1.RELEASE
  • org.springframework.expression-3.1.1.RELEASE
  • org.springframework.web-3.1.1.RELEASE
  • org.springframework.web.servlet-3.1.1.RELEASE
Finally copy struts2-spring-plugin-2.3.1.2 to WEB-INF/lib from your downloaded struts2 jars.

For configuring all above jars and struts 2 jars in your eclipse ide please refer configuring struts 2 link.

Project structure:

Web.xml:

Copy following content in web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Struts2Spring3IntegrationExample</display-name>
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <welcome-file-list>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Here you can note that we have configured listener.
org.springframework.web.context.ContextLoaderListner  is required to load spring configuration file.By default the applicationContext.xml file will be used for doing the Spring bean configuration and it must be same level as web.xml.

Action class:

Create action class named HelloWorld.java under package org.arpit.javaPostsForLearning in src folder.  
copy following content to HelloWorld.java.
package org.arpit.javaPostsForLearning;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport{
    String message;
    public String getMessage() {
  return message;
 }

    public void setMessage(String message) {
  this.message = message;
 }
    public String execute()
    {
   return SUCCESS;
    }
}
Now we will configure above action file in applicationContext.xml.

applicationContext.xml

Create applicationContext.xml in WebContent->WEB_INF. Copy following content to applicationContext.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="helloWorldClass" class="org.arpit.javaPostsForLearning.HelloWorld" >
        <property name="message" value="Hello World! from arpit" />
    </bean>
</beans>
 

JSPs:

We will create one jsp named "Welcome.jsp" under WebContent folder. Copy following code into Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 Tutorial</title>
</head>
<body>
<s:property value="message" />
</body>
</html>

struts.xml:

Create struts.xml in src folder. Copy following content in struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!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" namespace="/">
        <action name="HelloWorld" class="helloWorldClass">
            <result name="success">Welcome.jsp</result>
        </action>
    </package>
</struts>
Now you can note here that In <action> tag,we have set class attribute same as id of bean configured in applicationContext.xml.

Run Application:

Right click on project->run as->run on server.
copy http://localhost:8080/Struts2Spring3IntegrationExample/HelloWorld link to  browser and press enter.

Source Code :

click to begin
7.3MB .zip

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring
 The @Autowired annotation provides control over where and how autowiring can be done.This annotations can be done on setter method,contructor or property.We will see each in detail with example.

@Autowired on setter methods:

By default,whereever spring containers finds @autowire notation,it autowires bean byType. You can use @Autowire annotation on setter method to get rid of <property> tag in XML configuration file.

Example:

For configuring spring in your eclipse ide please refer hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.
package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

    String countryName;
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
    @Autowired
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java
package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.AutowiredAnnotationInSpringMain.java

This class contains main function.Create AutowiredAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into AutowiredAnnotationInSpringMain.java
 package org.arpit.javapostsforlearning;

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

public class AutowiredAnnotationInSpringMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
        Capital capital=countryObj.getCapital();
        String capitalName=capital.getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}

4.ApplicationContext.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: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:annotation-config/>
 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="countryName" value="India" />
 </bean>
 <bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>
As you can see there is no relationship between above two beans,but we have used @autowired annotation which will automatically wire above beans on the basis of type.

5.Run it:

When you will run above application,you will get following as output.
Delhi is capital of India

@Autowired on properties:

you can use @Autowired on property to get rid of setter method.Spring container automatically assign values to corresponding attributes.You don't need setter methods for that.Make following changes to above code:

Country.java:

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

    String countryName;

    @Autowired
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
}

Run it:

When you will run above application,you will get following as output.
Delhi is capital of India

@Autowired on Constructor:

you can use @autowired on constructor also and it will work even if you didn't define <constructor-arg> tag in XML configuration file.Make following changes to above code:

Country.java:

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

    String countryName;
    Capital capital;

    @Autowired
    public Country(String countryName, Capital capital) {
 super();
 this.countryName = countryName;
 this.capital = capital;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
}

ApplicationContext.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: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:annotation-config/>
 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <constructor-arg index="0" type="java.lang.String" value="India" />
 </bean>
 <bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>

Run it:

When you will run above application,you will get following as output.
Delhi is capital of India

@Autowired with Arugments:

By default,dependency is required in the case of @Autowired like @Required but you can turn off it by passing required=false to @Autowired as argument.

Country.java:

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

    String countryName;
    @Autowired(required=false)
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
}
Now it will run even if you don't provide capital bean in XML configuration.

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring
Spring supports JSR 250 Annotations such as @PostConstruct, @PreDestroy and @Resource annotations.Lets  discuss each in brief.

@Resource:

Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods. This is a common pattern found in Java EE 5 and Java 6 which Spring supports for Spring-managed objects as well.

@Resource takes name as attribute and by default Spring will interpret that value as the bean name to be injected. In other words, it follows by-name semantics.If you do not specify name attribute then it will interpret property name as bean name to be injected and then it will search in XML configuration file.

Example:

For configuring spring in your eclipse ide please refer hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

    String countryName;
   
    @Resource(name="capitalA") 
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.QualifierAnnotationInSpringMain.java

This class contains main function.Create QualifierAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into QualifierAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

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

public class QualifierAnnotationInSpringMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
        Capital capital=countryObj.getCapital();
        String capitalName=capital.getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}

4.ApplicationContext.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: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:annotation-config/>
 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="countryName" value="India" />
 </bean>
 <bean id="capitalA" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalNamehttp://www.blogger.com/blogger.g?blogID=1114068605611316469#editor/target=post;postID=2213204035101507334" value="Delhi" />
 </bean>
 <bean id="capitalB" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Mumbai" />
 </bean>
</beans>

As you can note here we are having two beans of same type.In Country.java we have used @Resource(name-"capitalA") it means we want to autowire capital property of country with bean id="capitalA" in XML configuration file.

5.Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

@PostContruct and @PreDestroy:

These annotations are alternative methods for defining initialization and destruction callback functions.
We have used all other method in Spring lifetime callbacks.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Country {

 String countryName ;
 
 public String getCountryName() {
  return countryName;
 }
 
 
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }

 @PostConstruct
 public void init()
 {
  System.out.println("In init block of country");
 }

 @PreDestroy 
 public void destroy()
 {
  System.out.println("In destroy block of country");
 }
}

2.LifetimeCallbacksMain.java

This class contains main function.Create LifetimeCallbacksMain.java under package org.arpit.javapostsforlearning.Copy following content into LifetimeCallbacksMain.java
package org.arpit.javapostsforlearning;

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

public class LifetimeCallbacksMain{

 public static void main(String[] args) {

  AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");
  System.out.println("Country Name: "+countryObj.getCountryName());
  appContext.registerShutdownHook();
 }
}
Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

3.ApplicationContext.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" init-method="init" destroy-method="destroy">
 <property name="countryName" value="India"/>
 </bean>
  
</beans>

4.Run it

When you will run above application,you will get following as output.


In init block of country
Country Name: India
In destroy block of country

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring
you can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.

Example:

For configuring spring in your eclipse ide please refer hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

    String countryName;
    @Autowired
    @Qualifier("capitalA") 
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.QualifierAnnotationInSpringMain.java

This class contains main function.Create QualifierAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into QualifierAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

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

public class QualifierAnnotationInSpringMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
        Capital capital=countryObj.getCapital();
        String capitalName=capital.getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}

4.ApplicationContext.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: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:annotation-config/>
 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="countryName" value="India" />
 </bean>
 <bean id="capitalA" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
 <bean id="capitalB" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Mumbai" />
 </bean>
</beans>

As you can note here we are having two beans of same type.In Country.java we have used @Qualifier("capitalA") it means we want to autowire capital property of country with bean id="capitalA" in XML configuration file.

5.Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

The @Required annotation applies to bean property setter methods, as in the following example:

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring
package org.arpit.javapostsforlearning;

public class Country {

    Capital capital; 

    @Required
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.

Suppose you have very large application and you get   NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Required;
public class Country {

    String countryName;
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }

    @Required
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.RequiredAnnotationInSpringMain.java

This class contains main function.Create RequiredAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into RequiredAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

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

public class RequiredAnnotationInSpringMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
        Capital capital=countryObj.getCapital();
        String capitalName=capital.getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}

4.ApplicationContext.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: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:annotation-config/>
 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="countryName" value="India" />
 </bean>
 <bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>

Now you can note here that we have not injected capital property into country class but we have used it for getting capitalName in RequiredAnnotationInSpringMain class.

5.Run it:

When you will run above application,you will get following as output.

Sep 01, 2012 1:43:16 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@17a1767: startup date [Sat Sep 01 13:43:16 IST 2012]; root of context hierarchy
Sep 01, 2012 1:43:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [ApplicationContext.xml]
Sep 01, 2012 1:43:17 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@54446d: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,CountryBean,CaptialBean,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Sep 01, 2012 1:43:17 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@54446d: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,CountryBean,CaptialBean,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CountryBean' defined in class path resource [ApplicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'capital' is required for bean 'CountryBean'
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.arpit.javapostsforlearning.SetterInjectionMain.main(SetterInjectionMain.java:11)
Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'capital' is required for bean 'CountryBean'
    at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:149)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    ... 11 more

When you run it,you will get exception complaining "Property 'capital' is required for bean 'CountryBean'"

This is 15 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
There are two ways via which you can inject dependency in spring
  1. By configuring XML.
  2. By using annotation.
In all our previous posts,we have injected dependency by configuring XML file but instead of doing this,we can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

You might think what if you have done both i.e.used annotations and XML both.In that case,XML configuration will override annotations because XML configuration will be injected after annotations.

Now annotations based configuration is turned off by default so you have to turn it on by entering <context:annotation-config/> into spring XML file.

ApplicationContext.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: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:annotation-config/>
 <!-- beans declaration goes here -->
</beans>

Now you are ready to use annotations in your code.Let us discuss few important annotations in spring

@Required:

 The @Required annotation applies to bean property setter methods.

@Autowired:

The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.

 @Qualifier:

The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.

 JSR 250 Annotations: 

Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.


 

Java tutorial for beginners Copyright © 2012