Thursday, 29 December 2011

Spring AOP

What is Aspect Oriented Programming:

Aspects help us modularize the crosscutting concerns like Logging, Security and Transactions etc.. A crosscutting concern is described as any functionality that touches multiple points of an application.

Logging is an example of this, as most of the methods in an application implement logging. Few methods can also have some security rules applied to them.

With AOP, you still define the common functionality in one place, but you can declaratively define how and where this functionality is applied without having to modify the class to which you’re applying the new feature. Crosscutting concerns can now be modularized into special classes called aspects. This has two benefits. First, the logic for each concern is now in one place, as opposed to being scattered all over the code base. Second, our service modules are now cleaner since they only contain code for their core functionality and secondary concerns have been moved to aspects.

AOP Terms

Like most other languages AOP has it's own jargon. It is defined in terms of Advice, Pointcut and Join Points.

Advice: Aspects have a purpose, the job that they are meant to do. In AOP terms the job of an Aspect is called an Advice.

 Advice defines what an when of an Aspect in addition to describing the job that an aspect will perform.

advice addresses the question of when to perform the job. Should it be applied before a method is invoked? After the method is invoked? Both before and after method invocation? Or should it only be applied if a
method throws an exception?

Spring aspects can work with five kinds of advice:
  1. Before — The advice functionality takes place before the advised method is invoked.
  2. After — The advice functionality takes place after the advised method completes, regardless of the outcome.
  3. After-returning — The advice functionality takes place after the advised method successfully completes.
  4. After-throwing — The advice functionality takes place after the advised method throws an exception. 
  5. Around — The advice wraps the advised method, providing some functionality before and after the advised method is invoked.
Join Points:
A join point is a 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. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

Pointcuts:
An aspect doesn’t necessarily advise all join points in an application. Pointcuts help narrow down the join points advised by an aspect.

If advice defines the what and when of aspects, then pointcuts define the where. A pointcut definition matches one or more join points at which advice should be woven. Often you specify these pointcuts using explicit class and method names or through  regular expressions that define matching class and method name patterns. Some AOP frameworks allow you to create dynamic pointcuts that determine whether to apply advice based on runtime decisions, such as the value of method parameters.

Aspects:
An aspect is the merger of advice and pointcuts. Taken together, advice and pointcuts define everything there is to know about an aspect—what it does and where and when it does it. 

Introductions:
Introductions allow us to add new methods and attributes to existing classes.

Weaving:
Weaving is the process of applying aspects to a target object to create a new proxied object. The aspects are woven into the target object at the specified join points. The weaving can take place at several points in the target object’s lifetime: 

Thursday, 22 December 2011

Hibernate


Hitting the Database with Spring 3.x




Basic Idea:

The Term DAO stands for Data Access Objects. DAOs do basic function of interacting with the database.
They contain database read/write logic and expose their functionality to the rest of the application via interfaces as shown in the figure below.



The philosophy of coding to interfaces has a couple of things to note..
  1. Your service layer that invokes DAO is testable now as you can provide a mock implementation of your DAOs Interface without event connecting to the database.
  2. Your service layer accesses the database in a database-agnostic manner. It does not need to know what database is being invoked by the DAO class. All it cares about is the interface methods.
One way spring helps you separate your data access tier from rest of your application is by providing a consistent Exception hierarchy that's used across all of it's DAO frameworks.

Spring's data access Exception hierarchy

 Plain vanilla JDBC forces you to handle SQLException. SQLException means that something went wrong while you were trying to access the database. It is tell what went wrong and how to handle it. Some common reasons of SQLException being thrown are
  • Application is not able to connect to the database.
  • Query being executed has syntax errors.
  • Table/Columns referred-to in the query doesn't exist.
  • An attempt to insert/Update values in database that violate a database constraint.
Most of the times when a SQLException is thrown, nothing much can be done to remedy it in a catch block. Most SQLExceptions represent FATAL conditions like application not being able to connect to the database. A query having a syntax error etc.. not much can be done to fix them on runtime.

Baisc Java Questions


Q 1: What happens if you don’t override equals method?
A: If you don’t override equals method then you won’t be able to use those objects as key in hashtable and you probably won’t get accurate Sets such that there are no conceptual duplicates.

Q2: How do you implement equals method?

A:    Suppose you have an Employee Class which looks like below
public class Employee{
         private long employeeId;
         private String name;
         private int salary;

         //... public getter and setter methods

         public boolean equals(Object other){
           if((other instanceof Employee) && 
              ((Employee)other).getEmployeeId() == this.employeeId){
              return true;
           }else{
              return false;
           }
        }
   } 
Q3:  What is equals contract?
A: Equals contract says that:
  1. It is reflexive. For any any reference value x, x.equals(x) should return true.
  2. It is symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) is true.
  3. It is transitive. For any reference values x, y and z, if x.equals(y) returns true and y.equals(z) returns true then x.equals(z) must return true.
  4. It is consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently returns true or consistently returns false, provided no information used in equals comparision on the object is modified.
  5. For any non-null reference value x, x.equals(null) should return false.
Q4: In How Many Ways can you create an object for a class in java?
A: There are four ways in which we can create an object for a class in java
  1. Using New Operator: like Test t = new Test();
  2. Using newInstance(): like
        Test t = (Test) Class.forName("").newInstance();
  1. Using Clone: like
Test x=new Test();
Test t=x.clone();
  1. Using Object Deserialization : like ObjectInputStream istream=new ObjectInputStream(some inputStream);

Q5: Can we create constructor for an abstract class?
A: Yes, we can create Constructor for abstract class. The constructor will be invoked while instantiating its subclass object. The constructor can be invoked explicitly by using super keyword.

Q3: Is it possible to override static method?

A: No it is not possible to override a static method. This because there is only 1 instance of a static method at class level.

Q4: Is it possible to access non-static method from a static method

A: No static method can not access non-static methods Java has two types of methods, instance methods and static methods. A static method can be accessed without creating an instance of the class. If you try to use a non-static method and variable defined in this class then the compiler will say that non-static variable or method cannot be referenced from a static context. Static method can call only other static methods and static variables defined in the class.
 

Q5: Why is Java not fully object oriented?

A: In order to be fully object oriented a language must support classes, objects, inheritance and polymorphism. C++ is fully object oriented as it supports all the types of inheritances i.e. single, multilevel, multiple, hierarchical and multipath inheritances and if talk about polymorphism, C++ supports static binding and operator overloading which come under static polymorphism.

Java is not fully object oriented as Java does NOT support operator overloading and multiple inheritances Java supports multiple inheritance through interfaces though.

Q6: What is the difference between class variable, member variable and automatic(local) variable.
A: Instance variables are shared among thread while local variables are not shared. Instance variables are also shared among method invocations while local or automatic variables are created fresh for each invocation. Ie. Instance variables persist their value among method invocations while local variables are destroyed as and when their scope block ends, and are recreated each time the method is invoked.

Q7: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD com compile successfully?
A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;