Friday 30 March 2012

Spring Core Elongate


BeanFactory is lightweight because it does not create the objects while reading the xml ,the objects are created while calling getBean() secondly,it does not support i18N.

ApplicationContext creates all the objects while reading xml file and it supports Event Handling and i18N that’s why it is heavy weight.

If you want any bean to be declared as singleton then use scope="singleton" or singleton="true" (Attribute is version based).

To execute some logic automatically once the object is constructed after injecting the values [ it’s not possible using static because static is executed while class is loading] or to  throw an Exception if we are not injecting required values for beans we can implement afterPropertiesSet()  method of IntializingBean .

Ex1:-
       JndiObjectLocator implements IntializingBean
      {
           afterPropertiesSet()
           {    
               throw Exception;
            }
        }
JndiObjectLocator implemented afterPropertiesSet() method  to throw an exception if we are not injecting the dependent jndi name value.

   <bean id=“datasource”  class=“…JndiObjectFactoryBean”>
               <property name=“jndi”>
                          <value>MyJndi</value>
               </property>
    </bean>

here JndiObjectFactoryBean extends JndiObjectLocator so if your not injecting jndi name to the JndiObjectFactoryBean then afterPropertiesSet() method ofJndiObjectLocator will throw an Exception.

LocalSessionFactoryBean implements afterPropertiesSet() method of IntializingBean to create sessionFactory object after injecting the ORM details and it implements the destroy() of DisposableBean to close SessionFactory object.If we are not injecting  sessionFactory to HibernateTemplate then to throw an llegalArgumentException they are implemented afterPropertiesSet().

We can write init() ,destroy() methods in the bean without implementing any interface but we need to configure those using init-method and destroy-method attributes,  here we can give any name init() or initTest() etc.
    Ex:- <bean id=“xx” init-method=“initTest()” />

If any Bean is implementing DisposableBean then we need to implement destroy() method,we can also write another destroy method using destroy-method =“destroyTest()” attribute but first lifecycle method destroy() is executed then destroyTest() is executed.

If Bean is implementing IntializingBean(afterPropertiesSet()) and you are written init-method=“initTest()” then first afterPropertiesSet() is executed after this initTest() is executed.

 How to make your bean as abstract:

If some of the properties are common for two or more beans instead of configuring in each bean we can configure the common properties in one bean and make the bean as abstract  using abstract=“true”.
 We can utilise the common properties in other beans using parent attribute
 
Ex:- 
 <bean  id="ParentCB" class="org.spring.controller.MainController"
    abstract="true">
                     <property name="initRequestAction" value="init" />
                     <property name="homePageView" value="home"/>
</bean>

<bean  id="LoginCB" class="org.spring.controller.LoginController" parent="ParentCB">
                 <property name=“successView” value=“home”/>
</bean>
  
<bean id="PersonMaintainCB" class="org.spring.controller.PersonController"
 parent="ParentCB">
                 <property name="successView" value="person"/>
 </bean>

here initRequestAction and homePageView properties are common for all the controllers.
  

How to call static factory method:

To call static method we are using  classname  and the method returns some value based on return type,   to do this in spring use factory-method attribute
            class Employee
           {
               public static String getEmpName()
              {
                     return “Ram”;
               }
           }

<bean id=“empFactory” class=“Employee” factory-method=“getEmpName “>
</bean>
The above configuration will not return the Employee object it will return the static method(getEmpName())return value.

How to call non static factory method:

To get the non static method return value first configure the bean because it’s a non static  method, next configure another bean using factory-bean and factory-method attributes.

Ex:
         class Employee
        {
          public String getEmpName()
         {
           return “Ram”;
        }
        }
    
   <bean id=“employee” class=“Employee”/>
   <bean  id=“empFactory”  factory-bean=“employee”
    factory-method= getEmpName”/>
 

Use of Autowiring:

Instead of configuring the dependent properties we can use autowiring.  

i) autowire=byName :

Ex:   Class Service                                     
        {      private Dao dao;
                void   setDao()
               { 
                       
               }
          }

Without Autowiring :

<beans>
<bean  id=“dao” class=“. .MyDao”/>
<bean id=“service” class=“..MyService” >
         <property name=“dao”>……………….this code is not require in autowiring .
                     <ref bean=“dao”/>
        </propety>
</bean>
</beans>

With Autowiring :

<bean  id=“dao” class=“. .MyDao”/>
<bean id=“service” class=“..MyService”  autowire=“byName”/>

ii) autowire=byType:

if the setter method name  is not based on the  property then byName will not work(choose byType here) 

 Ex:-  public class Service
        {
            private Dao dao;
            public void setDaoOne(Dao dao)
            {
                    this.dao=dao;
            }
         }
Note: byType means not based on the arg-type.

Bean Configuration With Autowiring:

<bean  id=“dao” class=“. .MyDao”/>
<bean id=“service” class=“..MyService”   autowire=“byType”/>

iii) autowire=constructor:

 Ex:-    public class Service
          {
              private Dao dao;
              public Service(Dao dao)…………constructor
              {
                    this.dao=dao;
              }
          }

With out autowiring :

<bean  id=“dao” class=“. .MyDao”/>
<bean id=“service” class=“..MyService”>
      <constructor-arg>
                     <ref-bean=“dao”/>
      </constructor-arg>………… This code is not required
</bean>

Note:in autowiring   <constructor-arg> configuration is not required. 

With autowiring:

<bean  id=“dao” class=“. .MyDao”/>
<bean id=“service” class=“..MyService”   autowire=“constructor”/>

 iv) autowire=autodetect:

      If there is any arg -constructor then autowire=“constructor” is applied  otherwise autowire=“byType” is applied

Note:
1.If there is any complex dependency then don’t use autowiring  it will give ambiguty problems.
2.If you want to apply autowiring for all beans use default-autowire inside <beans> tag

      ex:   <beans default-autowire=“byName”>
                        configure the required beans here…….autowire will apply for all.
              </beans>

 

  How to configure Collection objects:

If the setter method arg-type is  String[]    then we can use <list> or<set>
If the setter method arg-type is List then we can use <list>
If the setter method arg-type is Set then we can use <set>
If the setter method arg-type is Properies  use <props>  and to define each key-value pairs  using <prop> tag inside <props>

Ex        
     public class Employee
    {
            private Properties employeeProperties;
            public void setEmployeeProperties(Properties employeeProperties)
           {
               …………….
            }
    }

<bean id=“employee” class=“.. Employee”>
         <property name=“employeeProperties”>
              <props>
                     <prop key=“name”>
                            <value>Kathy</value>
                     </prop>
                     <prop key=“id”>
                             <value>1771</value>
                     </prop>
             </props>
        </property>
</bean>

If the setter method arg-type is  Map then we can use <map>  and inside map each entry using <entry> tag

Public class Employee
{    private Map employeeMap;
      public void setEmployeeMap(Map employeeMap)
      {…………….}
 }

<bean id=“employee” class=“.. Employee”>
<property name=“employeeMap”>
         <map>
                 <entry key=“ename"><value>Jay</value></entry>
                 <entry key=“eid”><value>1771</value></entry>
      </map>
</property>
</bean>

 Property Name Space:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      xmlns:p=“http://www.springframework.org/schema/p“  />
Public class Employee
{   
      private String    ename;
      private int eid;
      //setters and getters;
}

<bean id=“employee” class=“.. Employee”   p:ename=“Jay”  p:eid=1771 />

s

  







Thursday 29 March 2012

Spring Core (use of dependency injection and Inversion of Control)


 The most fundamental feature of the Spring Framework is IOC and Dependency Injection. Container  resolves dependent components by setting implementation Object  instead of Component Instantiation.Most of the code in Spring is reduced using Dependency Injection and some part of the code (Exception logic ,Transaction Logic )required in Service and DAO classes is  reduced using AOP(Aspect Oriented Programming).Even AOP can simplify Security and Logging Logic etc..

Spring does not provide its own ORM but we can integrate spring with any existing ORM’s. Generally ORM can simplify Persistence logic (JDBC Code) if we are integrating ORM with Spring we can get all features that are provided by Spring(Dependency Injection, Exception Logic, Txn Logic ,Security ,Logging etc..)


Spring provides its own MVC and it is completely based on Dependency Injection
Spring can also be integrated with J2EE Technologies such as EJB,RMI,JMS etc… .


org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IOC container that is responsible for containing and otherwise managing the configured beans. BeanFactory Provides implementation of FactroryPattern  which removes the need of programmatic singleton.


Instantiating a Spring IoC container :
Resource resource = new FileSystemResource(“Spring-config.xml");   
BeanFactory factory = new XmlBeanFactory(resource);
(OR) 
ClassPathResource resource = new ClassPathResource(“spring-config.xml");
BeanFactory factory = new XmlBeanFactory(resource); 


The most commonly used BeanFactory implementation is the XmlBeanFactory class. In terms of XML The XmlBeanFactory takes this XML configuration meta data and uses it to create a fully configured system or application. BeanFactory reads spring-config.xml file and checks if singleton is true or false for configured beans (default is true) if it is true it will create the object once and kept that object In static HashMap and whenever the object is required return the object from Hashmap , if it is false create the object every time and return that  object directly .After Reading config file Container create objects  using Reflection API and while creating to the constructor it will pass argument values using java.lang.reflect.Constructor then once the object is created container will call the setter methods using that object


The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring's AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in web applications.

Bean Class:-

package com.springcore;
public class Person
{  
         private String  personID;
         private String name;

         Person(String  id)
        {
            this.personID=id;          
        }
        public void setName(String name)  //-------------setter method for Name
       {   
            this.name=name;
       }
       public String getName()
       { 
            return name;
        } 
         
      // Here Setter and Getter for personID field

       public void message() //------we are calling this method using spring given object.
       {                  
           s.o.p(“Welcome “+name);                                                        
       }                              |
}                                  // Here value for the name field is configured in xml file so spring can inject this value to the property while creating the object

   spring-config.xml:--

 <beans>
     <bean id=“person”  class=“com.springcore.Person”>
        <constructor-arg  index=“0” type=“java.lang.String”>
           <value>Trigyn171</value>
         </constructor-arg>
        <property name=“name”>
          <value>Rammohan</value>
       </property>
     </bean>
</beans> 

   Test class :-
        Class Test
{
         public static void main(String[ ] args)
        {
              //Activating Spring Container
             BeanFactory factory=new XmlBeanFactory(“spring-config.xml”);
              //creating and getting the bean object
            Person person=(Person)factory.getBean(“person”);
                                |                                                |…….//bean id
                                |….//Spring creates the object and given to the user
           person.message();
       }
         }

 
  • If the setter method arg type is List we can use <list> tag inside  <property> tag
  • If the setter method arg type is Set then we can use <set> tag inside <property> tag
  • If the setter method argument  type is Map then we can use <map> and <entry>combination inside <property> tag

Ex:-
       <property name=“argument”>
              <map>
                <entry key=“id” value=“1”/>
                <entry key=“name” value=“ram”/>
              </map>
        </property>

      If the setter method argument  type is Properties then we can use 
     <prop> tag inside props> tag

      //private Properties p;

     <property name=“p” >
         <props>   
         <prop key=“name”>   <value>Ram</value>    </prop>
            <prop key=“marks” value=“100”>
         </props>
     </properties>



Java Basics-Part 1


A java source file can contain any number of classes but at most one class can be declared as public. If there is a public class, compulsory the name of the public class and the name of the source file must be matched otherwise Compile Time Error.If there is no public class, any name we can provide for java source file and there is no restriction.



Example:-
class A
{

}
class B
{

}
class C
{

}

Case -1:- If there is no public class then we can use any name as filename, there is no restriction in this case. File Name: “A.java” (or)” B.java” (or) “C.java “.

Case-2:- If class B declared as the public, then compulsory the name of the source file must be “B.java”, otherwise we will get compile time error.
Compile Time Error: - class B is public, should be declared filename as B.java.

Case-3:-If both A&B declared as public and the name of the source file is B.java, then we will get  Compile Time Error: - class A is public, should be declared filename as A.java.

Note:-It is always a good programming practice to maintain only one class for source and we can maintain that class name as source file name.

Import Statement:-

class Test
{
   public static void main(String[] args)
  {
     ArrayList al = new ArrayList();
   }
}

Compile Time Error:-can’t find symbol ArrayList.

We can resolve this problem by using fully qualified name.
       java.util.ArrayList al = new java.util.ArrayList();

the problem in this approach , using fully qualified name reduces the readability of the code.We can resolve this by using import statements.

import java.util.ArrayList;
class Test
{
    public static void main(String[] args)
   {
       ArrayList al = new ArrayList();
   }
}
 i.e., import statements simply acts as typing shortcut &improves readability of the code.

#include vs. import:-


In the case of #include all the required header files will be loaded at the beginning only.

But in the case of import the specified classed won’t be loaded at the beginning.Whenever we are using a particular class, then only corresponding class will be loaded. i.e., import statement follows load-on-fly.

Types of import statements:-

1. Explicit class import [import java.util.ArrayList] : It improves readability of the code, recommended to use.

2. Implicit class import [import java.util.*;] :  Not recommended to use because it reduces readability of the code.

Q) Which of the following import statements are valid?
i. import java.util.*;------------------------------Valid
ii. import java.util.ArrayList;------------------ Valid
iii. import java.util;------------------------------Not Valid
iv. import java.util.ArrayList.*;--------------Not Valid

Example1:

class MyObject extends java.rmi.UniCastRemoteObject
{

}
The above code compiles fine, even though we are not using import statement because we are using fully qualified name.

Example2:

import java.util.*;
import java.sql.*;
class Test
{
   Public static void main(String[] args)
  {
     Date d= new Date();
   }
}
Compile Time Error: - reference to Date is ambiguous, both classes java.util.Date and java.sql.Date

Note:-Even in the case of List (interface) also we can face the same ambiguity problem.Because it is available in both util and awt packages.

While resolving class names compiler will always gives the precedence in the following order.

1. Explicit class import.
2. Class name present in current working directory.
3. Implicit class import.

Whenever we are importing a package, sub package classes won’t be imported.

Ex: - 
import java.util.*;- in this case java.util.regex package classes won’t be
imported. If you want to import any of the regex package classes then its required to write one import statement (import java.util.regex.* ;)

import statement is totally compile time issue, there is no impact on runtime, more no of imports more will be the compile time. It is not required to import the members of the following packages because these are available by default for every java programmer.

i.java.lang package classes
ii.Current working directory classes[default package]

 

Static import:

 This concept is introduced in 1.5, According to static import, it improves readability. But according to worldwide experts it reduces the readability and increases the confusion of the code. Hence if there is no specific requirement, it is not recommended to use it. Whenever we are using static import it is not required to use class name while accessing static members.

Without static import:-

package com.basics;
import java.lang.*;


public class StaticImport
{
    // without static import
     public static void main(String[] args)
     {
          System.out.println(Math.sqrt(4)); // 2.0
          System.out.println(Math.random()); // 0.7138941126607322
          System.out.println(Math.max(10,20)); // 20
     }
}

With static import:-

package com.basics;
import static java.lang.Math.sqrt;
import static java.lang.Math.*;

//this class will explain the purpose of static imports.
public class StaticImport
{
      // with static import
      public static void main(String[] args)
      {
            System.out.println(sqrt(4));-----------// 2.0
            System.out.println(random());----------//0.2807616256825275
            System.out.println(max(10,20));--------// 20
       }
}

While resolving static members, compiler will always gives precedence in the following order.


1. Current class static members.
2. Explicit static import.
3. Implicit static import.

Example:-

package com.basics;
import static java.lang.Integer.MAX_VALUE;------(2)
import static java.lang.Byte.*;-----------------(3)
public class StaticPrecedence
{
   static int MAX_VALUE=888;------------------(1)
   public static void main(String[] args)
  {
     System.out.println(MAX_VALUE);
   }
}

  •  If we are commenting line-1,explicit static import will be considered and we will get output of Integer class MAX_VALUE (2147483647)
  • If we are commenting lin-1 and line-2 then Byte class MAX_VALUE will be consider and 127 as the output.
  • It is never recommended to use import concept until method level or variable level.But we have to use only at class level i.e., general import recommended to use, but not static import.

Q.Which of the following import statements are valid?
1. import static java.util.Date.*;----------valid
2. import static java.util.ArrayList;
3. import java.util.ArrayList;
4. import static java.lang.Math.sqrt;------valid
5. import java.util.ArrayList.*;
6. import java.lang.math.*;
7. import static java.lang.math.*;

Packages:-

  •  It is an encapsulation mechanism to group related classes & interfaces into a single module. The main purpose of the package statement is to resolve naming conflicts. There is universally accepted naming convention to name the packages. i.e. to use internet domain in reverse.
Ex: com.apple, com.veeram, com.icici etc...

package  com.veeram;
public class PackagesTest
{
    public static void main(String[] args)
   {
        System.out.println("Packages Demo");
    }
 }

compile 1 : javac  PackagesTest.java 
//The generated .class file will be placed in current working directory [default package].

comile 2 :  javac –d D: PackagesTest.java 
//the generated .class file will be placed in corresponding package structure.

If the specified package structure is not available then this command itself be create that structure.If the specified destination is not available then we will get compile time error.

Example:-
Compile:Javac -d Z: PackagesTest.java // the system can’t find the path specified.
Run:Java packages.PackagesTest // use fully qualified name to run the class.
Conclusion: - for any java source file there should be at most one package statement.
package pack1;
package pack2;--C.T.E
class Test
{

}

The Following is the valid structure of java source file.

1. Package statement--------------At most one.
2. Import statements--------------Any Number.
3. Class/interface declarations---Any Number.

Q. which of the following is valid sequence of statements in java source file?

1. import, package, class
2. package, import, class
3. import, class, interface
4. import, interface, class

Answer: 2,3,4 are valid sequence of statements

Q. which of the following are valid java source file?

1. empty file.
2. file contains only one statement which is import.
3.file contains only one statement which is package.

Answer: All options are valid.

Class level modifiers:-

Whenever we are using our own java classes compulsory we have to provide the information to the JVM.

1. Whether this class is accessible from anywhere or not.
2. Can we allowed to create an object of this class or not.
3. Shall we allowed to create child class or not.

We can specify this information by using corresponding modifiers.

   1.The only applicable modifiers for top level classes are :
        public, default, final, abstract and strictfp.
  If we are using any other modifier we will get compile time error.

  2 An inner class can be declared with the following modifier.
        public, default, final, abstract, strictfp, private, protected, static.

private Test
{

}..................compile time error: modifier private not allowed here.

Public classes:-

If a class is declared as public then we can access that class from anywhere.

package pack1;
public class A
{
   public void m1()
   {
      System.out.println("Hello");
    }
}

package pack2;
import pack1.A;
public class B
{
     public static void main(String[] args)
    {
        A a= new A();
        a.m1();
    }
}

If a class A is not declared as public then while compiling B class we will get “pack1.A is not public in pack1” can’t be accessed from outside package.

Default class:- 

 If a class declared as default then we can access that class only in current package but not from outside package.The default access is also known as package level access

Final classes:- 

Final is the modifier applicable for classes, methods and variables.Whatever the parent is by default available to the child through inheritance if the child is not satisfied with parent class implementation then child can override the  implementation in its own way. If the child is not allow to override [to meet security constraints ] then such type of methods we have to declare with final modifier i.e. final methods can’t be overridden .



package com.finalmodifier;
public class Parent
{
   public final void m1()
  {

   }
}
class Child extends Parent
{
   public void m1()
  {

  }
}
compile time error : m1() in Child can’t override , m1() in Parent overridden method is final.

If a class declared as final then we are not allow to create the child class
final class P
{
}
class C extends P
{

}
compile time error : can’t inherit from final P

Note:- The main advantage of final keyword is we can achieve security but the main limitation of final keyword is we are missing the key benefit of inheritance and polymorphism. Hence if there is no specific requirement it is not recommended to use final keyword.