Tuesday, April 29, 2014

AOP in Spring

Aspect Oriented Programming:

Before dive into Spring AOP, let me explain the problems faced in my previous projects(he he i am not going to explain my problems with my dumb manager :P)  Ours is an Internet Banking solution.So we need to audit the important fund transfer actions(SaveFT, SubmitFT,AuthorizeFT and RejectFT) in case if something goes wrong, the bank can see the audit and find out who saved or submitted a particular operation.So they can do the necessary actions.

Coming to auditing functionality, this is scattered in most of the classes and any changes to the audit functionality we need to change all classes it was implemented.So even though my actual business logic wasn't change we need to change those classes and need to compile and deploy again which is pain and error prone.Some of the cross cutting functionalities are logging,security,auditing and transaction management.

AOP on the other hand provide solution to the above cross cutting concerns or cross cutting functionalists.
We dont need to write these concerns in side our business classes, we can write these aspects separately and run our advices at run time at the desired target methods.AOP also reduces the boiler plate code across our application.

Terminology in Spring AOP;

1)Aspect: Aspect is the cross cutting functionality in our application like logging,auditing,transaction or security.

2)Advice: Advice is the job of an Aspect.Advice will define what and when of an aspect.In addition to describing the job of an aspect will perform, advice addresses the question of when to perform the job

Spring aspects can work with five kinds of advices

a)Before: Advice will run before the invocation of our target method.
b)After: Advice will run after the completion of our target method regardless of the outcome.
c)After-returning: The Advice functionality takes place after the target method completed successfully.
d)After-throwing: The Advice funcionality takes place after the target method throws an exception.
e)Around: Advice will run before and after our target method.

3)Join Points: A join point is point in the execution of the application where an aspect can be plugged in.
This point could be a method being called, an exception being thrown, or even a field being modified.But in Spring join points only represent methods.We can use join points and methods synonymously.
These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

4)Pointcut: Pointcuts are used to pinpoint where an aspect’s advice should be applied. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP.

Lets write a small Logging aspect to understand AOP implementation in Spring.

For example i have a bank account and i want to run this logging functionality to run before and after the deposit method.

BankAccount.java


package com.ramesh.domain;  
 public class BankAccount {  
      private long balance;  
      // method to deposit  
      public void deposit(int depositAmount) {  
           if (depositAmount < 0) {  
                System.out.print("Invalid Amount!");  
           }  
           balance = balance + depositAmount;  
           System.out.println("Current Balance is "+balance);  
      }  
      // method to withdraw  
      public int withdraw(int withdrawAmount) {  
           System.out.println("Your Balance is: " + balance);  
           if (withdrawAmount > balance) {  
                System.out.println("You do not have a sufficient balance to withdraw this amount!");  
           }  
           return withdrawAmount;  
      }  
 }  

LoggingAspect.java:

This aspect has two advices which we want to run BankAccount.java's deposit method.Keep in mind the BankAccount doesnt aware about this logging aspect.Spring creates a proxy and weaves these advices in the runtime.

package com.ramesh.domain;  
 public class LoggingAspect {  
      public void beforeDeposit() {  
           System.out.println("Running before deposit method");  
      }  
      public void afterDeposit() {  
           System.out.println("Running After Deposit method");  
      }  
 }  


Now lets configure our application-context.xml to include these two bean definitions and configure the before and after pointcuts.

 <?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   
   http://www.springframework.org/schema/aop   
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  
      <bean id="bankAccount" class="com.ramesh.domain.BankAccount" />  
      <bean id="logging" class="com.ramesh.domain.LoggingAspect" />  
      <aop:config>  
           <aop:aspect ref="logging">  
                <aop:before pointcut="execution(* com.ramesh.domain.BankAccount.deposit(..))"  
                     method="beforeDeposit" />  
                <aop:after pointcut="execution(* com.ramesh.domain.BankAccount.deposit(..))"  
                     method="afterDeposit" />  
           </aop:aspect>  
      </aop:config>  
 </beans>  


We are configuring the aop in xml file.We can do this with annotations also.

Here we declared these two beans.There is no dependency between these two beans.we are defining logging bean as an aspect. and we want to execute before method at our target method com.ramesh.domain.BankAccount.deposit. please note * at starting the pointcut denotes we never care about the return type and deposit(..) indicates the method can take any number of parameters.

Since we completed our configuration lets test it..

package com.ramesh;  
 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 import com.ramesh.domain.BankAccount;  
 public class MainApp {  
      public static void main(String[] args) {  
           ApplicationContext appContext = new ClassPathXmlApplicationContext(  
                     "spring-context.xml");  
           BankAccount account = (BankAccount) appContext.getBean("bankAccount");  
           account.deposit(100);  
      }  
 }  


If you see the main program, we only calling the deposit method.Lets see the output after running this

Apr 29, 2014 8:50:33 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1c0e45a: defining beans [bankAccount,logging,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1]; root of factory hierarchy


Running before deposit method
Current Balance is 100
Running After Deposit method

Magic...our advices(beforeDeposit() and afterDeposit() methods) run before and after our target method(deposit())..

we have seen before and after advice.Now lets see around advice.

Around advice will run before and after the target method.This advice will be useful when we want to save the state between the before and after advice calls, if we don't have around advice we need to save the state to a variable when before and after advices used.

Around advice will take ProceedingJoinPoint as an parameter and it has proceed method will is used to pass the control to our target method.

Lets say we want to run around advice to a target method withdraw in BankAccount

package com.ramesh.domain;  
 public class BankAccount {  
      private long balance=1000;  
      // method to deposit  
      public void deposit(int depositAmount) {  
           if (depositAmount < 0) {  
                System.out.print("Invalid Amount!");  
           }  
           balance = balance + depositAmount;  
           System.out.println("Current Balance is "+balance);  
      }  
      // method to withdraw  
      public long withdraw(int withdrawAmount) {  
           System.out.println("Your Balance is: " + balance);  
           if (withdrawAmount > balance) {  
                System.out.println("You do not have a sufficient balance to withdraw this amount!");  
           }  
           balance=balance-withdrawAmount;  
           return balance;  
      }  
 }  


 package com.ramesh.domain;  
 import org.aspectj.lang.ProceedingJoinPoint;  
 public class LoggingAspect {  
      public void beforeDeposit() {  
           System.out.println("Running before deposit method");  
      }  
      public void afterDeposit() {  
           System.out.println("Running After Deposit method");  
      }  
      public void aroundWithdraw(ProceedingJoinPoint joinPoint) {  
           System.out  
                     .println("Inside around method: It will run before advised method");  
           try {  
                joinPoint.proceed();  
           } catch (Throwable e) {  
                e.printStackTrace();  
           }  
           System.out  
                     .println("Inside around method: It will run after advised method");  
      }  
 }  


Lets see the around configuration in spring-context.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   
   http://www.springframework.org/schema/aop   
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  
      <bean id="bankAccount" class="com.ramesh.domain.BankAccount" />  
      <bean id="logging" class="com.ramesh.domain.LoggingAspect" />  
      <aop:config>  
           <aop:aspect ref="logging">  
                <aop:around pointcut="execution(* com.ramesh.domain.BankAccount.withdraw(..))"  
                     method="aroundWithdraw" />  
           </aop:aspect>  
      </aop:config>  
 </beans>  


Lets run the MainApp.java to the output

package com.ramesh;  
 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 import com.ramesh.domain.BankAccount;  
 public class MainApp {  
      public static void main(String[] args) {  
           ApplicationContext appContext = new ClassPathXmlApplicationContext(  
                     "spring-context.xml");  
           BankAccount account = (BankAccount) appContext.getBean("bankAccount");  
           account.withdraw(100);  
      }  
 }  


Output:

Apr 30, 2014 12:27:32 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@982589: defining beans [bankAccount,logging,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0]; root of factory hierarchy


Inside around method: It will run before advised method
Your Balance is: 1000
Inside around method: It will run after advised method


Thanks for reading!!!!!!

Monday, April 28, 2014

Object Oriented Programming - Encapsulation

Encapsulation in Object Oriented Programming is a concept in which it enforces protecting attributes and behavior by wrapping inside a single unit(a class in Java) and restricting accessing to the inner workings of the objects based on that class.The true power of encapsulation is that the changes done to our protected code will result in bare minimal changes or no change to other parts of the application.

In principle the object shouldn't reveal any thing about it's inner workings and provides only things that are necessary for other parts of the application to work.

We can do this in Java by completely encapsulate a member variable or member function by declaring them as private or you can encapsulate partially by declaring them protected.

Let me give an example

Lets say we have a BankAccount class and we don't want other parts of the program reach in my balance and change it without going through the usual withdraw() or deposit() methods.This will cause a havoc in my program.

You may ask, we are allowing to change the balance through the deposit and withdraw methods.Yes.But how can my balance updated without doing any withdraw or deposit operations.In these two methods we may be doing other things like auditing or logging, without this functionality we might not know what's happened if some thing goes wrong(like who done the transfer and how much amount or who authorized the transaction etc).

To secure the data we should declare those attributes as private.We are not secretive here we are reducing the dependencies in other parts of the program.So any changes done in my program won't affect other parts of the application.

package com.ramesh.domain;  
 import java.util.Date;  
 public class BankAccount {  
      private String accountId;  
      private long balance;  
      private String accountType;  
      private Date dateOpened;  
      public void withdraw() {  
           System.out.println("Inside withdraw");  
      }  
      public void deposit() {  
           System.out.println("Inside deposit");  
      }  
      // setters and getters  
 }  


Advantages:

1) Easy to change our code with new requirements without affecting other parts of the program.
2) Easy for unit testing.
3) Let us control who can access what.

That's all about Encapsulation...Thanks for reading !!!!!







Spring Beans Auto-Wiring

We can configure Spring beans dependencies using <property>  and <consturctor-arg>.But Spring container can auto wire relationships between collaborating objects without using the above mentioned tags.This will allow us to minimize the amount of XML configuration in our Spring Context xml file.But we need to be very careful using auto wiring as this will be difficult if some thing goes wrong and new developers in the team hard to debug how the beans auto wired.

There are 4 ways we can do the bean auto wiring.By default there is no auto wiring and we need to explicitly mention if we need to let the container know how our beans should be auto wired.

1)byName
2)byType
3)constructor
4)autodetect

Lets see each type in action

1)byName: auto wiring by name. If we defined auto wiring byName in bean definition file then Spring container looks at the properties of the bean and tries to match the name of the property and if both matches it wire its properties.

Lets see in action.For example if i have a Employee and Address classes and Address is declared as an instance field in Employee class.

Employee.java


package com.ramesh.domain;  
 public class Employee {  
      private int id;  
      private String name;  
      private long salary;  
      private Address address;  
      public int getId() {  
           return id;  
      }  
      public void setId(int id) {  
           this.id = id;  
      }  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public long getSalary() {  
           return salary;  
      }  
      public void setSalary(long salary) {  
           this.salary = salary;  
      }  
      public Address getAddress() {  
           return address;  
      }  
      public void setAddress(Address address) {  
           this.address = address;  
      }  
 }  

Address.java


package com.ramesh.domain;  
 public class Address {  
      private String street;  
      private String pinCode;  
      private String city;  
      public String getStreet() {  
           return street;  
      }  
      public void setStreet(String street) {  
           this.street = street;  
      }  
      public String getPinCode() {  
           return pinCode;  
      }  
      public void setPinCode(String pinCode) {  
           this.pinCode = pinCode;  
      }  
      public String getCity() {  
           return city;  
      }  
      public void setCity(String city) {  
           this.city = city;  
      }  
 }  


 spring-context.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:mvc="http://www.springframework.org/schema/mvc"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xsi:schemaLocation="  
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
     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">  
      <bean id="employee" class="com.ramesh.domain.Employee" autowire="byName">  
           <property name="id" value="844" />  
           <property name="name" value="Ramesh M" />  
           <property name="salary" value="85000" />  
      </bean>  
      <bean id="address" class="com.ramesh.domain.Address">  
           <property name="street">  
                <value>Embassy Golflinks Business Park Street</value>  
           </property>  
           <property name="city">  
                <value>Bangalore</value>  
           </property>  
           <property name="pinCode">  
                <value>560071</value>  
           </property>  
      </bean>  
 </beans>  


If you notice these lines in our xml file, we didn't mention the address either as a property or a constructor-arg.We mentioned another attribute autowire="byName" for which the Spring container will check a bean name "address" and match both the property mentioned in employee bean and xml file and autowires them

<bean id="employee" class="com.ramesh.domain.Employee" autowire="byName">
<property name="id" value="844" />
<property name="name" value="Ramesh M" />
<property name="salary" value="85000" />
</bean>

I will explain about the other auto wiring in a while...

Thanks for reading !!!!!!

Sunday, April 27, 2014

Binary Search-Sample program in Java

What is Binary Search by the way?

A binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.[1][2] For binary search, the array should be arranged in ascending or descending order. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.
(Source: WikiPedia)

The requirement for binary search algo is the array should be sorted.We can use Quick Sort or Merge Sort for sorting the array.First we need to take mid element(if low=0 and high=array.length-1 then mid=low+high/2).If the middle element is the one which we are searching we return the index or we just print the element is found in the array at a specified index.

Lets say the element we are searching is less than the middle element then we will take the sub array by specifying high=mid-1 or if the searching element is greater than the middle element then our sub array becomes low=mid+1.This process will continue until we found the element we are searching.

Code:

/**
 * @author RameshM
 * 
 *         Sample program for Binary Search
 */
public class BinarySearchTest {

 public static boolean searchKey(int[] intArray, int element) {

  int low = 0;
  int high = intArray.length - 1;

  while (low <= high) {
   int middle = (low + high) / 2;
   if (element > intArray[middle]) {
    low = middle + 1;
   } else if (element < intArray[middle]) {
    high = middle - 1;
   } else {
    return true;
   }
  }
  return false;
 }

 public static void main(String args[]) {

  int[] intArray = { 2, 4, 5, 8, 9, 22, 44, 55, 66, 88, 100 };

  int element = 44;

  boolean result = searchKey(intArray, element);

  if (result) {
   System.out.println("The element found in the Array");
  } else {
   System.out.println("The element is not found in the Array");
  }

 }
}

Output:

The element found in the Array

Java 1.7 features

Below are the important features introduced in 1.7 in developers point of view.

1)Strings in switch statement
2)The try-with-resources Statement
3)Binary Literals
4)Underscores in numerical Literals
5)Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
6)Type Inference for Generic Instance Creation

Injecting inner beans in Spring

Similar to Java which provides defining inner class inside another class, Spring IOC provides defining a bean inside another bean.This will be useful when a bean is declared as property in another bean.

Let us see the inner bean in action

Lets say i have an Employee bean and employee has an address object declared as a field in Employee object.

Employee.java:


package com.ramesh.domain;

public class Employee {

 private int id;
 private String name;
 private long salary;
 private Address address;

 public int getId() {
  return id;
 }

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

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public long getSalary() {
  return salary;
 }

 public void setSalary(long salary) {
  this.salary = salary;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

}

As shown above employee as a Address field.Lets see the Address bean

Address.java

package com.ramesh.domain;

public class Address {

 private String street;
 private String pinCode;
 private String city;

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getPinCode() {
  return pinCode;
 }

 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

}

Now configure the spring-context.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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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">


 <bean id="employee" class="com.ramesh.domain.Employee">
  <property name="id" value="844" />
  <property name="name" value="Ramesh M" />
  <property name="salary" value="85000" />
  <property name="address">
   <bean class="com.ramesh.domain.Address">
    <property name="street">
     <value>Embassy Golflinks Business Park Street</value>
    </property>
    <property name="city">
     <value>Bangalore</value>
    </property>
    <property name="pinCode">
     <value>560071</value>
    </property>
   </bean>
  </property>

 </bean>

</beans>

Since we completed the configuration lets test 

package com.ramesh;

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

import com.ramesh.domain.Employee;

public class MainApp {

 public static void main(String[] args) {
  ApplicationContext appContext = new ClassPathXmlApplicationContext(
    "spring-context.xml");
  Employee employee = (Employee) appContext.getBean("employee");

  // displaying employee name
  System.out.println(employee.getName());

  // displaying inner bean address details

  System.out.println(employee.getAddress().getStreet());

 }
}

The output:

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1b4fad5: defining beans [employee]; root of factory hierarchy
Ramesh M
Embassy Golflinks Business Park Street


Spring bean scopes

Below are the list of Spring scopes

1)singleton: By default all the beans created in Spring are singleton per container.If you not mention scope attribute in your bean definition file beans then beans will created are singletons only.

2)prototype:  New bean will be created for each request with this scope.You can override the default singleton scope to prototype in bean definition file as shown below.

<bean id="account" class="com.ramesh.Account" scope="prototype">

3)request:Scopes a bean definition to a HTTP request.Valid only in the case of web application context(E.g.: Spring MVC)

4)session: Scopes a bean definition to a HTTP session.Valid only the case of web application context(E.g.: Spring MVC)

5)global-session: Scopes a bean definition to a global HTTP session.Valid in the case of Portlets context

Creating Spring beans using Factory method

We all know we never need to create bean dependencies in Spring with new operator like below

e.g   Employee employee=new Employee();


Usually we use constructor or setter methods to inject dependencies.But there are other ways we can create objects in Spring.In some classes its possible that there wont be any public constructor available(E.g.: Creating java singletons objects).In these cases we don't have any option other than using the factory patterns to create objects in Spring.

Please note if you are testing the beans with private constructor in a normal java program using main program, it wont be a problem.Spring is able to create beans with private constructors using reflection.But if there is a SecurityManager in place and it wont let create beans with private constructors.

1)Static factory method:Let's say we have a static factory which is responsible for creating Singleton object(Java base Singleton object).We can use Spring bean factory-method attribute in our Spring bean definition file to wire the object.
2)Instance factory method: These objects are created using the bean instance.

Let us see creating bean instance using Static factory method and Instance factory method in action.

Lets say i have Account interface with few methods and SavingsAccount and CurrentAccount implement this interface

Account.java


 public interface Account{  
 void deposit();  
 void withdraw();  
 }  

SavingsAccount.java


public class SavingsAccount{  
 public void deposit(){  
 System.out.println("Inside Deposit method");  
 }  
 public void withdraw(){  
 System.out.println("Inside Withdraw method");  
 }  
 }   

CurrentAccount.java


public class CurrentAccount{  
 public void deposit(){  
 System.out.println("Inside Deposit method");  
 }  
 public void withdraw(){  
 System.out.println("Inside Withdraw method");  
 }  
 }   


Now we need a factory to create SavingsAccount and CurrentAccount instances.

public class AccountService{  
      private static AccountService service = new AccountService();  
      //Static factory method  
      public static AccountService createService(){  
           return service;  
      }  
      //Instance factory methods  
      public Account createSavingsAccountInstance(){  
           return new SavingsAccount();  
      }  
      public Account createCurrentAccountInstance(){  
           return new CurrentAccount();  
      }  
 }  


Now lets see how to configure bean definition file to call these factory methods.

These below two are important attributes in our spring context file to call the factory instance method and factory bean methods

1) factory-method
2)factory-bean

application-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:context="http://www.springframework.org/schema/context"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="  
 http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
 http://www.springframework.org/schema/context  
 http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
      <bean id="accountService" class="com.ramesh.AccountService" factory-method="createService"/>  
      <bean id="createSavingsAccountInstance" factory-bean="accountService" factory-method="createSavingsAccountInstance"/>  
      <bean id="createCurrentAccountInstance" factory-bean="accountService" factory-method="createCurrentAccountInstance"/>  
 </beans>  



Lets test this code

com.ramesh;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 public class SpringApplicationContextLoader{  
      public static void main (String args[]){  
           ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");  
           Account savings = (SavingsAccount)applicationContext.getBean("createSavingsAccountInstance");  
           savings.withdraw();  
           Account current = (CurrentAccount)applicationContext.getBean("createCurrentAccountInstance");  
           current.deposit();  
      }  
 }  



I hope you get the concept :-)

Thanks for reading!!!!!








Design patterns used in Spring

Here is a list of important design patterns used in Spring

1)Singleton
2)Model View Controller
3)Front Controller
4)ViewResolver
5)Observer
6)Service Locator
7)Proxy
8)Template method


Thanks for reading!!!!!!

How can a class extends another class, extends Object? Is it not multiple inheritance which is not allowed in Java?


Let me explain

We know every class in java extends Object class.Lets say if you have a class Employee

public class Employee{  
 private String name;  
 // getters and setters  
 }  

Then this class implicitly like this

public class Employee extends Object{  
 private String name;  
 // getters and setters  
 }  


But if your class extends another class explicitly then 

 public class Employee extends BaseEmployee{  
 private String name;  
 // getters and setters  
 }  

Then your Employee class doesn't extends Objects class.Instead your BaseEmployee will extends Object class.

Hope you get it ;)

Saturday, April 26, 2014

Spring Bean Life Cycle


Lets see the life cycle of bean from cradle to grave or in another words from instantiation to destroy method.

Once Spring reads the bean definition xml file

1) Spring instantiates the bean.
2) Spring injects the values and bean references into bean references.
3) If your bean implements the BeanNameAware interface, Spring calls the setBeanName() method.
4) If your bean implements BeanFactoryAware interface then Spring calls the setBeanFactory() method and passing the bean factory itself.
5) If your bean implements ApplicationContextAware interface then Spring calls the setApplicationContext() method.
6) If your bean implements BeanPostProcessor interface then Spring calls postProcessBeforeInitialization() method
7) If your bean implements InitializingBean interface then Spring calls afterPropertiesSet() method and if your bean declared any init-method then the specified init method will be called.
8) If there are any beans that implements BeanPostProcessor then Spring calls postProcessAfterInitialization() method.
9) Now your bean is ready and will be available till the application context is destroyed.
10) If your bean implements DisposableBean interface then Spring will call destroy method similarly if your bean declared any user defined destroy method then Spring calls the destroy-method.

Thanks for visiting my blog....

Friday, April 25, 2014

Java 1.5 features

Java 1.4 -> Java 1.5

These are the most important features added in Java 1.5

1)Generics
2)Enhanced for loop
3)Auto Boxing and Unboxing
4)Type Safe Enums
5)Varargs
6)Static Imports
7)Annotations or Metadata

There are other changes also but the above are the important from the developer's perspective.

Tuesday, April 22, 2014

Dependency Injection in Spring

What is Dependency Injection?

In Layman's Language: In any Object oriented programming language, objects depends on each other and they collaborating on each others by calling their methods. Traditionally we create objects using new operator as shown below.

Lets say i have Employee class and this employee class has a reference of Department object, we create the department object inside Employee class like shown below

public class Employee{  
 private Department dept=new Department();  
 public void displayMessage(){  
 dept.displayDeptDetails();  
 }  
 }   
Did you notice any problem in the above code?

Yes.You guessed it correct. 

The code is tightly coupled.For example if i need to create the department object in another way or simply put if i need to change any changes to department object i need to change the Employee class and if the reference in say in 100 classes in my project i need to change in 100 classes and need to rebuild and redeploy it and possibly insert some bugs if you forget to modify some class(no one is perfect and as developers we keep making mistakes otherwise why the hell the testing teams required :P)

Spring provides solution for this problem in the form of dependency injection.Spring let us configure how the dependencies needs to be created in an xml file/annotation and it will inject the dependencies at run time.


A sample bean declarations in xml file


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="employee" class="com.ramesh.Employee">
       <constructor-arg ref="department"/>
   </bean>                                                                         <bean id="department" class="com.ramesh.Department">                         </bean>                                                                   </beans>

We have different bean container implementations for BeanFactory or ApplicationContext.

E.g.:
package com.ramesh;  
 import org.springframework.context.ApplicationContext;  
 import org.springframework.context.support.ClassPathXmlApplicationContext;  
 public class EmployeeMain{  
 public staticvoidmain(String[]args){  
 ApplicationContextcontext=  
 new ClassPathXmlApplicationContext("EmployeeContext.xml");  
 Employee emp=(Employee)context.getBean("employee");  
 dept.displayDeptDetails();  
 }   
 }  When the Spring application reads this xml file it will instantiates the beans and assign a unique id as described in the bean configuration.Now the beans along with their dependencies are ready for use.Since the dependencies injected at run time this will be called Dependency Injection. Most people use Inversion of Control and Dependency Injection interchangeably.

 But IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will 'depend' on in order to behave correctly.


Thanks for reading!!!!!!!

Saturday, April 19, 2014

Welcome to Extreme Java

Hello Folks,

My self Ramesh Mandala.I am a Senior Java Developer in  a reputed MNC in Bangalore.I have experience in JAVA/J2EE and related frameworks for more than 8+ years.I am writing this blog for sharing my knowledge.Let me know if some thing wrong in the content so i can correct it. You can comment on the post or you can reach me at ramesh.mandala@gmail.com

Thanks for visiting my blog!!!!!!!

Cheers,

Ramesh