Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday, May 29, 2014

Spring MVC

Introduction:
              Spring MVC has the most flexible architecture to develop web applications in java/spring environment.It provides clear separation of different layers components, with this MVC Architecture we can use different types front-end technologies like Jsp,freemaker etc.

Basic architecture and flow of Spring MVC Architecture


Dispatcher Servlet: 'Dispatcher Servlet'  which receives  requests and forward them to controllers and also allows to use Other all Features.It traps and takes the requests  and dispatches them to the appropriate controllers with the help of Handler Mappings.

Handler Mapping: Handles the execution of a list of pre-processors and post-processors and controllers if they match certain(Ex: matching URL specified with a controller).It maps requests with Intended Controllers.

Controller: Controller interpret user input and transforms it into a model that represented to the user by View. It serves the user requests and returns Model and View Object.

ViewResolver:  resolves view names to views.

View:  A view is a generated HTML output to the User.

Lets take an Example to explain flow of Spring MVC.

1. Take a new DynamicWebApplication in your IDE with name 'Spring3MVC'.
                       

    
2. go to WEB-INF  Folder and Add the following code to web.xml file.

 <!-- Dispatcher Servlet -->    <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

By adding the above code we are configuring the 'DispatcherServlet'  or Front Controller which controls the entire application execution flow of control.

3. Next add some list of jar file as shown below in lib Folder.
          
     

I am using spring 3.2.2 in my application.you can get 'commons-logging.jar' from spring 2.5 and download 'jstl.jar' .

4.Add a Controller class to service/process client request.
In my application i want to display some 'hello world ' kind of message so i use my     Controller to do this.add this controller in some package like 'com.controller'

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

   @RequestMapping("/hello")
   public ModelAndView helloWorld() {

       String message = "Hello World, Spring 3.2.2..!!";
       return new ModelAndView("hello", "message", message);
   }
}


In the above code there are 2 Annotations
  •       @Controller
  •       @RequestMapping("/hello")
 @Controller-tells to spring that this bean is a Controller bean to process client  
                         requests.
@RequestMapping("/hello")-tells to spring that this bean should process all the requests beginning  with '/hello'. 

This controller returns Model and View Object with a message ''Hello World, Spring 3.2.2..!!".

5. To display this result to the client we need View.we are using jsp in view layer. So we have to create a jsp with name hello.jsp. place this jsp file in WEB-INF/jsp folder.

    

the code in hello.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>hello</title>
    <title>Spring 3.2.2 MVC: Hello World</title>
</head>
<body>
    ${message}
</body>
</html>

This 'message' displays Hello World, Spring 3.2.2..!! ,Because message is the name in Model and View Object which return by the Controller.

And also we need one more jsp to send request, for this take a jsp with name 'index.jsp' and place in in /WEB-INF/jsp/ Folder.


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Spring 3.2.2 SpringMVC</title>
</head>
<body>
    <a href="hello.htm">demo request</a>
</body>
</html>

make this 'index.jsp' as the welcome file for Application,to do this add following code to web.xml file.

<display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list>

Finally we need spring bean configuration file with name 'springmvc-servlet.xml'. Because when DispatcherServlet initialized it looks for file with name [value of <servlet-name> tag in DispatcherServlet configuration]-servlet.xml in WEB-INF Folder.So in our example the spring bean configuration file name should be ''springmvc-servlet.xml".

This file contains Handler Mappings, ViewResolvers, Controllers and Other Spring Bean configuration.
our file contains

<?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"
.......>

     <context:component-scan  base-package="com.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 '<context:component-scan  base-package="com.controller" />' tag tells Spring to load components from 'com.controller' package and it's sub packages.
The ViewResolver  bean resolves the view and add prefix  '/WEB-INF/jsp/' and suffix '.jsp' . In this app Controller HelloWorldController have return Model and View Object with view hello ,this resolver resolves that to '/WEB-INF/jsp/hello.jsp'.

Final structure of Application
                  


Flow:
1. request sent from index.jsp.

2. DispatcherServlet traps and Takes the request and dispatches it to Controller HelloWorldController by looking at HadlerMapping(this was done by annotations).

3. Controller HelloWorldController process use request and returns a Model and View Object with View name hello and other details.

4. DispatcherServlet resolves the view name to '/WEB-INF/jsp/hello.jsp' by looking at into ViewResolver Configuration in Spring bean configuration file springmvc-servlet.xml. The hello.jsp rendered by the spring and send to the client.

That is the end of Spring MVC First App.


Monday, April 14, 2014

Auto wiring in Spring

Assigning  dependent values to spring bean resources is technically known as "WIRING". There are 2 types in wiring. They are

  • Explicit wiring                                             
  • Auto wiring
Explicit wiring: 
The setter injection,constructor injections are considered as explicit wiring. In this approach programmer has to pass/provide dependent value the spring container to inject to the reference bean.

Auto wiring: 
In this approach spring container itself choose the dependent value to assian to resource. To let Spring container do this we use '<autowire>' attribute in bean tag.

There are 4 types of auto wiring,
byName:  
In this type of auto wiring the spring container assigns value to the dependent bean by  name of the bean property, i.e the id of the dependent bean object and the name of the spring bean property must be same.
In this approach spring container use setter injection to assign value.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
* @return the uname
*/
public String getUname() {
return uname;
}
/**
* @param uname the uname to set
*/
public void setUname(String uname) {
this.uname = uname;
}
/**
* @return the date
*/
public Date getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(Date date) {
this.date = date;
  System.out.println("date: "+date);
}
}

MainApp.java 
//MainApp.java
public class MainApp{
public static void main(String a[]){
FileSystemResource res=new FileSystemResource("beans.xml");
XmlBeanFactory factory=new XmlBeanFactory(res);
Demo beanobj=(Demo)factory.getBean("demobean");
}
}

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="byName">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

with the  autowire="byName"  the spring container look for  bean object which has 'date' as id (here date is property name)  if found assigns to the resource other wise no value will be assigned.

byType:
In this type of auto wiring the spring container assigns value to the dependent bean by  type(data type) of the bean property, i.e the type(data type) of the dependent bean object and the type(data type) of the spring bean property must be same.
In this approach spring container use setter injection to assign value.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

DemoBean.java & MainApp.java are same,but change in beans.xml

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="byType">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

with the  autowire="byType"  the spring container look for  bean object 'java.util.Date'  type if found assigns to the resource other wise no value will be assigned.
If more than one 'java.util.Date'  type object found in spring configuration file Exception will be thrown by container.

constructor:
In this type of auto wiring the spring container assigns value to the dependent bean through parameterized constructor  of bean , i.e the the spring container calls
parameterized constructor to assign dependent values to the resource.This is similar to byTtype  mode.

Look at the following example ...how a java.util.Date value is assigning to the bean
in this example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

in this example MainApp.java is same and changes are needed in beans.xml,
DemoBean.xml.

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="constructor">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
 * @return the uname
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}
/**
*constructor
**/
public DemoBean(Date d){
date=d;
  System.out.println("date: "+date);
}
}

with the  autowire="constructor"  the spring container look for  bean object 'java.util.Date'  type if found assigns to the resource otherwise Exception will be thrown by container.
If more than one 'java.util.Date'  type object found in spring configuration file Exception will be thrown by container.

autodetect:
In this mode of auto wiring spring container first try to assigns a value to dependent bean using constructor mode if this mode is not possible then container go to byType mode, i.e if we place a constructor in bean class container choose constructor mode else you place setter methods container use byType mode.

Lets take the same example

beans.xml (spring configuration file)
DemoBean.java (spring bean)
MainApp.java (client program)

in this example MainApp.java is same and changes are needed in beans.xml,
DemoBean.xml.

beans.xml
//beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
............................>

    <bean id="demobean" class="DemoBean" autowire="autodetect">
     <property name="uname" value="raju"/>
    </bean>

<bean id="date" class="java.util.Date"/>
</beans>

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;

 /**
 * @return the uname                                                                  1
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}

/**
*constructor
**/
public DemoBean(Date d){
date=d;
  System.out.println("constructor autowiring: "+date);
}
}

DemoBean.java 
//DemoBean.java
public class DemoBean{
private String uname;
private Date date;
                                                                                                             2
 /**
 * @return the date
 */
public Date getDate() {
return date;
}
/**
 * @param date the date to set
 */
public void setDate(Date date) {
System.out.println("setter method autodetect: "+date);
this.date = date;
}

 /**
 * @return the uname
 */
public String getUname() {
return uname;
}
/**
 * @param uname the uname to set
 */
public void setUname(String uname) {
this.uname = uname;
 System.out.println("uname:  "+uname);
}
}

with 1 'DemoBean.java' spring container performs constructor based auto wiring and
with 2 'DemoBean.java' spring container performs byType(setter injection) based auto wiring.
if neither constructor nor setter method found container don't assign a value.

Limitations of Autowiring:
  1. Autowiring is possible only on reference type Bean Propertied(we can inject only object,simple values can not be injected).
  2. There is chance of getting ambiguity.
  3. Kills readability of spring configuration file.


Wednesday, April 9, 2014

Bean Scopes in Spring

Spring Provides Multiple types of Scopes.Here we can consider scope is availability of bean Object.The different types of scopes are
  1. singleton                                                             
  2. prototype
  3. request
  4. session
  5. globalsession

singleton: The singleton means creating only one object/ instance per JVM.
The class which allow to create only one object per JVM is known as singleton class.
  • This is the default scope of spring bean.
  • spring container returns the same object every time you access  from BeanFactory or ApplicationContext objects.

Ex for specifying scope in spring configuration file of a bean is

<bean id="beanid" class="beanclass" scope="singleton"/>
                                              or
<bean id="beanid" class="beanclass" scope="singleton">
....
...
</bean>

for singleton scope no need to specify it in spring configuration file ,because it is the default scope.

prototype: In this prototype scope the spring container creates and returns a new object for each time when you access  from BeanFactory or ApplicationContext objects.

Ex for specifying scope in spring configuration file of a bean is

<bean id="beanid" class="beanclass" scope="prototype"/>
                                              or
<bean id="beanid" class="beanclass" scope="prototype">
....
...
</bean>

request:
  • The request scoped bean object will be created one per HTTP request .
  • This bean object will become request object attribute value.
Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="request">
....
...
</bean>

  • With the above bean definition  the Spring container will create a brand new instance of the LoginAction bean using the 'loginAction' bean definition for each and every HTTP request.
  • When the request is finished the bean that is scoped to the request will be discarded.
  • It is useful only in web Environment.

session:
The session scoped beans will be created one per HTTP session.
This bean object will become HTTP session scope object.

Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="session"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="session">
....
...
</bean>

  • With the above bean definition  the Spring container will create a brand new instance of the LoginAction bean using the 'loginAction' bean definition for each and every HTTP session.
  • When the HTTP session is finished the bean that is scoped to the session will be discarded.
  • It is useful only in web Environment.

globalsession: 
  • This is similar to the session scope.
  • But this is useful in Spring based portlet development environment.
Ex for specifying scope in spring configuration file of a bean is

<bean id="loginAction" class="com.foo.LoginAction" scope="globalsession"/>
                                                            or
<bean id="loginAction" class="com.foo.LoginAction" scope="globalsession">
....
...
</bean>

These are the scopes in Spring Framework.

Saturday, March 29, 2014

Spring Containers


  • Spring Containers are Provided to take care of Spring Beans Life Cycle.
  • Spring containers are also perform Dependency Injection on Spring beans in 2 ways, in configuration file every bean/resource configured with '<bean>' tag.
  • If we use '<property>' tag to perform dependency injection then container performs 'setter-injection' ,if we use '<constructor-arg>'    tag to perform dependency injection  then container performs 'Constructor-Injection' mode dependency injection.
  • The Java classes that we are using as resources of spring application are called as Spring Resources.
  • To configure these Spring Beans we need Spring configuration file. 'anyname'.xml can be taken as spring configuration file.
  • Underlying container will use this configuration file to recognize resources.
Spring Provides 2 containers,They are
  1. BeanFactory                                                          
  2. ApplicationContext
BeanFactory:
  • To Activate 'BeanFactory'  we need an Object of class which implements "org.springframework.beans.factory.BeanFactory"  interface.
  • "org.springframework.beans.factory.xml.XmlBeanFactory" is most commonly used implementation class of 'BeanFactory' interface.
  • To create Object of 'XmlBeanFactory' we need 'FileSystemResource' Object

Activating 'BeanFactory' Container.....

//Creating a resource
FileSystemRecource res=new FileSystemResource("springcfgfile.xml");
                                   or
ClassPathResource res=new ClassPathReosurce("springcfgfile.xml");

//Activate 'BeanFactory' container.
XmlBeanFactory factory=new XmlBeanFactory(res);


FileSystemResource: locates the given spring configuration file from the specified path of File System.

ClassPathResource: locates the given spring configuration file from the directories & jars that are added in class-path.

ApplicationContext:
  • ApplicationContext container is Enhancement of BeanFactory Container. 
  • To Activate 'ApplicationContext'  we need an Object of class which implements "org.springframework.context.ApplicationContext"  interface.
  • There are 3 popular classes implementing the this Interface

  • FileSystemAmlApplicationContext: Activates Spring Container by reading the spring configuration file from the specified path of 'File System'.
FileSystemXmlApplicationContext context=new FileSystemXmlApplicationContext("springconfigurationfile.xml");
                                                   or
ApplicationContext context=new FileSystemXmlApplicationContext("springconfigurationfile.xml");
  • ClassPathXmlApplicationContext: Activates Spring Container by reading the spring configuration file from the class path folders & jars.
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("springconfigurationfile.xml");
                                                 or
ApplicationContext context=new ClassPathXmlApplicationContext("springconfigurationfile.xml");
    • WebXmlApplicationContext: Activates Spring Container by reading the spring configuration file from web application resources(in web environment).

    Monday, March 24, 2014

    Dependency Injection

    " If The Underlying Technology or server or run-time environment or Framework is assigning dependent values to resources Dynamically even though the resources are not satisfying any contract,then it is called Dependency Injection".

    This type of approach is also called Inversion of Control.

    Majorly there are 2 types of Dependency-Injections.
                                 
    • Setter Injection.                                                       
    • Constructor Injection.

    setter Injection:
    •  In setter Injection approach we use setter & getter Methods to assign dependent values to resources dynamically. 
    • To Configure these methods in spring configuration file we use '<property>' tag.
    • These setter methods will be called after Constructor  creation of that resource(POJO) class.
    Eg configuration:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"................>

     <bean id="fb" class="firstbean">

    <property name="msg" value="hai..!"/>
    (or)<!-- You Can Use Either one of these ways. -->
    <property name="msg">  
    <value>     hello    </value>
    </property>

    </bean>
    </beans>

    in the above example   'msg'  is the name of the property of resource.

    Example application on spring setter injection.
    In this application i have
    jar files:
    commons-logging.jar
    spring-beans-3.2.2.RELEASE.jar
    spring-context-3.2.2.RELEASE.jar
    spring-core-3.2.2.RELEASE.jar
    spring-expression-3.2.2.RELEASE.jar

    You can get all the spring jars from spring 3.2.2 software and the commons-logging from spring 2.5.

    UserImpl class:
    It Contains Business Logic.

    package com.javagreat.springSI;

    import java.util.Calendar;
    import com.javagreat.springSI.Interface.User;

    public class UserImpl implements User {
    String msg;

    /**
    * @return the msg
    */
    public String getMsg() {
    return msg;
    }

    /**
    * @param msg the msg to set
    */
    public void setMsg(String msg) {
    this.msg = msg;
    }

    @Override
    public void displayMsg(String user_name) {
    Calendar c=Calendar.getInstance();
    int h=c.get(Calendar.HOUR_OF_DAY);
    if(h<12){
    System.out.println(msg+" Good Morning "+user_name);
    }else if(h<16){
    System.out.println(msg+" Good Afternoon "+user_name);
    }else if(h<20){
    System.out.println(msg+" Good Evening "+user_name);
    }else {
    System.out.println(msg+" Good Night "+user_name);
    }
    }
    }


    Spring Configuration file:
    To Configure Beans.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    .......................>

    <bean id="userbean" class="com.javagreat.springSI.UserImpl">
    <!-- <property name="msg">
    <value>Hello...!</value>
    </property>
    -->
    <!-- You Can Use Either one of these ways. -->
    <property name="msg" value="Hai...!"></property>
    </bean>
    </beans>

    Userdemo class:
    This is to run the Application.

    package com.javagreat.springSI;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    import com.javagreat.springSI.Interface.User;

    public class UserDemo {
    public static void main(String s[]){
    ApplicationContext context=new FileSystemXmlApplicationContext("/Context.xml");
    User ui= (UserImpl) context.getBean("userbean");
    ui.displayMsg("raju");
    }
    }

    With this Application we can inject dependent values to resource from Outside(xml file). In This demo application we injected a string value But,in real time we need to inject 'Datasource','connection'  etc objects.

    Constructor Injection:

    • In Constructor Injection we use parameterized  constructors to assign dependent values to resources.
    • To pass dependent values to these parameterized  constructors we use '<constructor-arg>' in spring configure   file. 
    • In Constructor Injection dependent values will be assigned to resources at the time of object creation.
    Example Configuration:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"................>

     <bean id="fb" class="firstbean">

    <constructor-arg  value=''hello"/>

    (or)<!-- You Can Use Either one of these ways. -->

    <constructor-arg >
    <value>     hai    </value>
    </constructor-arg>

    </bean>
    </beans>

    When Spring Container reads the above data it generates a 1-param constructor and assigns hello/hai to property of the 'firstbean' class.

    Constructor-Injection based example application is contains  same files as setter-injection based application.But small changes are need in spring configuration file and  UserImpl class.

    UserImpl class:
    It Contains Business Logic.

    package com.javagreat.springSI;

    import java.util.Calendar;
    import com.javagreat.springSI.Interface.User;

    public class UserImpl implements User {
    String msg;

    public UserImpl(String msg){
    this.msg=msg;
    }//This is the only change needed in this file.

    @Override
    public void displayMsg(String user_name) {
    Calendar c=Calendar.getInstance();
    int h=c.get(Calendar.HOUR_OF_DAY);
    if(h<12){
    System.out.println(msg+" Good Morning "+user_name);
    }else if(h<16){
    System.out.println(msg+" Good Afternoon "+user_name);
    }else if(h<20){
    System.out.println(msg+" Good Evening "+user_name);
    }else {
    System.out.println(msg+" Good Night "+user_name);
    }
    }
    }

    Spring Configuration file:
    To Configure Beans.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    .......................>

    <bean id="userbean" class="com.javagreat.springSI.UserImpl">
    <!-- <constructor-arg>
    <value>Hello...!</value>
    </constructor-arg>
    -->
    <!-- You Can Use Either one of these ways. -->
    <constructor-arg value="Hai...!"/>
    </bean>
    </beans>

    Except these 2 changes Everything is same as above example. If you run the above application with these changes you can assign dependent value through constructor.

    Thursday, March 20, 2014

    What is Spring?


    Definition:
    "Spring is a Open-Source, Light-Weight , Loosely Coupled and Dependency Injection Based  Aspect-Oriented Java/J2EE Application Framework."
                                         

    Come To Each Word...

    Open-Source:  As You Know Open-Source software  Means available at Free of Cost to Users and also Allows public to Provide enhancements and Modifications to The Software under some Licences(free).

    Light-Weight: Some Components required High-End Web servers or Application Servers to Run and Resources of these components also should be implemented by Involving the component's  APIs, but
    • Most of Spring  applications can run outside of web/Application servers.
    • Spring supplies two light weight containers they can activate without server also. 
    • The Resources of Spring Applications can be implemented without using spring API (as POJO & POJI).
    B'coz of These reasons SPRING called as Light-Weight.

    Loosely Coupled: If Degree of Dependency is less B/w components then those components called as Loosely Coupled components. Spring is also Loosely Coupled because of

    • The Dependent Values required for Spring Application can be supplied from out-side of app Through Xml files & Properties Files.
    • We Can Use Spring Modules Individually or Together in Application Development.
    • We can Integrate Spring other Java, JEE Technologies and F/Ws in Project Development. 

    Dependency Injection: If The Underlying Technology or Framework or Servlet or Run-time Environment is Dynamically pushes/assigns dependent values to the resources  even though  they are not satisfying any contract, then is is called Dependency Injection. This approach is also called  Inversion of Control.

    Aspect-Oriented: Spring is Aspect-Oriented Because it provides Provision to Apply Aspects/Middle ware Services on Spring Application.
    Spring allows us to apply middle ware services through Spring Aop Module, Aspectj.
               

    Saturday, February 8, 2014

    Activation of Spring Container in Web Application

                                               
    One of the ways to Activate Spring 'ApplicationContext'  Container is
    First Configure the Spring configuration file in web.xml file
    eg:

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/Spring.cfg.xml</param-value>
    </context-param>


    and next Configure the ContextLoaderListener

    <listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
          </listener-class>
    </listener>


    and finally in Servlet


    ApplicationContext context=WebApplicationContextUtils.
    getRequiredWebApplicationContext(config.getServletContext());


    It is Done. Now ApplicationContext Container will be Activated.

    Wednesday, December 18, 2013

    Quartz Scheduler in Spring

     Quartz Scheduler is used to scheduling of all kinds of jobs. For this it uses Trigger, Job and JobDetail objects
       
                                               

     JobDetail objects contain all information needed to run a job. The Spring Framework provides a JobDetailBean that makes the JobDetail more of an actual JavaBean with sensible defaults

    For Ex:
    <bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="example.ExampleJob" />
    <property name="jobDataAsMap">
    <map>
    <entry key="timeout" value="5" />
    </map>
    </property>
    </bean>

    The timeout is specified in the job data map. The job data map is available through the JobExecutionContext (passed to you at execution time), but the JobDetailBean also maps the properties from the job data map to properties of the actual job. So in this case, if the ExampleJob contains a property named timeout,the JobDetailBean will automatically apply it.
    Ex:

    package example;
    public class ExampleJob extends QuartzJobBean {
    private int timeout;
    /**
    * Setter called after the ExampleJob is instantiated
    * with the value from the JobDetailBean (5)
    */
    public void setTimeout(int timeout) {
    this.timeout = timeout;
    }
    protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
    // do the actual work
    }
    }

    MethodInvokingJobDetailFactoryBean:
    Oftenly we need to invoke a method on a specific Class. The
    "MethodInvokingJobDetailFactoryBean" can do this exactly. 

    Ex Configuration:

    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="exampleBusinessObject" />
    <property name="targetMethod" value="doIt" />
    </bean>

    The above example will call the doIt method on the ExampleBusinessObject class.
    The class:

    public class ExampleBusinessObject {
    // properties and collaborators
    public void doIt() {
    // do the actual work
    }
    }

    Using the MethodInvokingJobDetailFactoryBean, we don't need to create one-line jobs that just invoke a method, and we only need to create the actual business object and wire up the detail object.

    By default Quartz jobs are stateless. Since they are stateless there is a possibility of interfering each other.

    If we specify 2 triggers for the same JobDetails there is a possibility of starting the second one before First one is Completed.

    To avoid this and to make jobs of 'MethodInvokingJobDetailFactoryBean'  
    non-concurrent set 'concurrent' flag to 'false'.


    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="exampleBusinessObject" />
    <property name="targetMethod" value="doIt" />
    <property name="concurrent" value="false" />
    </bean>

    Wiring up jobs using triggers & the 'SchedulerFactoryBean':

    We have created JobDetails and Jobs.
    we still needs to schedule the jobs themselves this can be done using 'triggers' and a 'SchedulerFactoryBean'.
    There are several triggers are available with in Quartz and Spring Provides 2 Quartz FactoryBean implementations with convenient defaults

    CronTriggerFactoryBean
    SimpleTriggerFactoryBean.

    Triggers need to be Scheduled.For this Spring offers a 'SchedulerFactoryBean' that exposes triggers to be set as properties.
    SchedulerFactoryBean schedules the actual jobs with those triggers.

    Ex. Configurations:

    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
    <!-- see the example of method invoking job above -->
    <property name="jobDetail" ref="jobDetail" />
    <!-- 10 seconds -->
    <property name="startDelay" value="10000" />
    <!-- repeat every 50 seconds -->
    <property name="repeatInterval" value="50000" />
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail" ref="exampleJob" />
    <!-- run every morning at 6 AM -->
    <property name="cronExpression" value="0 0 6 * * ?" />
    </bean>

    Now we've set up two triggers, 
    First one running every 50 seconds with a starting delay of 10 seconds and
    Second one runs every morning at 6 AM. And Finally we need to set up the

    SchedulerFactoryBean:

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
    <list>
    <ref bean="cronTrigger"/>
    <ref nean="simpleTrigger"/>
    </list>
    </property>
    </bean>

    there are some more properties to use.

    Scheduling in Spring

     The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks with the 'TaskExecutor' and 'TaskScheduler' ibsp;                                                                                     Spring also Provided Implementations of these Interfaces which supports  'Thread Pools' or delegation to CommonJ within an application server environment.

    Spring also features integration classes for supporting scheduling with the Timer, part of the JDK since1.3, and the Quartz Scheduler.

    Both of those schedulers are set up using a FactoryBean with optional references to Timer or Trigger instances, respectively. And, a convenience class for both the Quartz Scheduler and the Timer is available that allows you to invoke a method of an existing target object (analogous to the normal MethodInvokingFactoryBean operation).

    Spring's TaskExecutor interface has a single method execute(Runnable task) that accepts a task for execution based on the semantics and configuration of the thread pool.

    The TaskExecutor was originally created to give other Spring components an abstraction for thread pooling where needed. Components such as the ApplicationEventMulticaster, JMS's AbstractMessageListenerContainer, and Quartz integration all use the TaskExecutor abstraction to pool threads. However, if your beans need thread pooling behavior, it is possible to use this abstraction for your own needs.

    TaskExecutor types:
    There are a number of pre-built implementations of TaskExecutor

    SimpleAsyncTaskExecutor
    SyncTaskExecutor
    ConcurrentTaskExecutor
    and etc.

    Using a TaskExecutor:
    Spring's TaskExecutor implementations are used as simple JavaBeans
    as Following

    import org.springframework.core.task.TaskExecutor;

    public class TaskExecutorExample {
    private class MessagePrinterTask implements Runnable {
    private String message;
    public MessagePrinterTask(String message) {
    this.message = message;
    }
    public void run() {
    System.out.println(message);
    }
    }
    private TaskExecutor taskExecutor;
    public TaskExecutorExample(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
    }
    public void printMessages() {
    for(int i = 0; i < 25; i++) {
    taskExecutor.execute(new MessagePrinterTask("Message" + i));
    }
    }
    }

    As you can see, rather than retrieving a thread from the pool and executing yourself, you add your Runnable to the queue and the TaskExecutor uses its internal rules to decide when the task gets
    executed.
    To configure the rules that the TaskExecutor will use, simple bean properties have been exposed.

    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="queueCapacity" value="25" />
    </bean>
    <bean id="taskExecutorExample" class="TaskExecutorExample">
    <constructor-arg ref="taskExecutor" />
    </bean>

    Task Scheduler:

    In addition to the 'TaskExecutor' abstraction, Spring 3.0 introduces a TaskScheduler with a variety of methods for scheduling tasks to run at some point in the future.

    Methods in TaskScheduler Interface

    ScheduledFuture schedule(Runnable task, Trigger trigger);
    ScheduledFuture schedule(Runnable task, Date startTime);
    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);
    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);
    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);
    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);

    The simplest method is the one named 'schedule' that takes a Runnable and Date only. That will cause the task to run once after the specified time. All of the other methods are capable of scheduling tasks to run repeatedly. The fixed-rate and fixed-delay methods are for simple, periodic execution, but the method that accepts a Trigger is much more flexible.

    Trigger:

    public interface Trigger {
    Date nextExecutionTime(TriggerContext triggerContext);
    }

    The 'TriggerContex' is the most important part. It encapsulates all of the relevant data.The 'TriggerContext' is an interface (a 'SimpleTriggerContext' implementation is used by default). The methods are available for Trigger implementations.

    public interface TriggerContext {
    Date lastScheduledExecutionTime();
    Date lastActualExecutionTime();
    Date lastCompletionTime();
    }

    Trigger implementations:

    Spring provides two implementations of the Trigger interface. The most interesting one is the
    CronTrigger. It enables the scheduling of tasks based on cron expressions. For example the following
    task is being scheduled to run 15 minutes past each hour but only during the 9-to-5 "business hours"
    on weekdays.

    scheduler.schedule(task, new CronTrigger("* 15 9-17 * * MON-FRI"));

    And Another Implementations is

    implementation is a 'PeriodicTrigger' that accepts a fixed period, an
    optional initial delay value, and a boolean to indicate whether the period should be interpreted as a fixed-rate or a fixed-delay.