Showing posts with label SpringCore. Show all posts
Showing posts with label SpringCore. Show all posts

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.