Spring AOP tutorial -I



Delicious

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects.

AOP concepts:

Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in J2EE applications. In my words: a trigger which can affect the multiple classes a one point….
Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. In my words: a locus of points where execution will happen.
Advice: action taken by an aspect at a particular join point. Different types of advice include “around,” “before” and “after” advice. (Advice types are discussed below.) In my words : the action to be taken at the point.
Pointcut: a predicate that matches join points. 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, and Spring uses the AspectJ pointcut expression language by default. In my words a criteria used to locate point.
Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.

Consider the example:

Lets declare an interface:

public interface Foo {

Foo getFoo(String fooName,int age);

void getAfter();

void getBefore(String myName);

}

A class implementing the interface:

public class DefaultFooService implements FooService {

public Foo getFoo(String name, int age) {

return new Foo(name, age);

}

public void getAfter() {}

public void getBefore(String myName) {}

}

Till here we have simple java implementation.
Now let see come AOP concepts in picture.
Before – Now I want that before the getBefore() method is called I want to log message saying what is the parameter passed.
After – Also I want that once any method in the interface is called a message should be logged after it.
I have a class which will be called to satisfy the above criteria.

public class SimpleProfiler {

public void afterMethod() throws Throwable {

System.out.println(“After the method call”);

}

public void beforeMethod(String myName){

System.out.println(“My name is “+myName);

}

}

The afterMethod() will log message after any method is called and beforeMethod() will log message before getBefore() is called.
To configure this we will used xmlThis is how I configure my spring.xml.

<beans xmlns=http://www.springframework.org/schema/beans&#8221;

xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;

xmlns:aop=http://www.springframework.org/schema/aop&#8221;

xsi:schemaLocation=http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd&#8221;>

<!– this is the object that will be proxied by Spring’s AOP infrastructure –>

1 <bean id=“fooService” class=“DefaultFooService”/>

2

3 <!– this is the actual advice itself –>

4 <bean id=“profiler” class=“SimpleProfiler”/>

5

6 <aop:config>

7                <aop:aspect ref=”profiler”>

14 <aop:pointcut id=“aopafterMethod”

expression=“execution(* FooService.*(..))”/>

15 <aop:after pointcut-ref=“aopafterMethod”

method=“afterMethod”/>

16 <aop:pointcut id=“aopBefore”

expression=“execution(* FooService.getBefore(String)) and args(myName)”/>

17 <aop:before pointcut-ref=“aopBefore”

method=“beforeMethod”/>

</aop:aspect>

</aop:config>

</beans>

Let see how we have configure the AOP .

  • Line 1 is used to create a proxy AOP object..
  • Line 7 we define the aspect “SimpleProfiler” class which will come into picture at different point-cuts.
  • Line 6 is used to configure the AOP.
  • Line 14 defines a pointcut in which an expression needs to mention. In this case the expressions say that “call afterMethod of SimpleProfiler class for any method declared inside the FooService interface.
  • Note Line 14 doesn’t define when to call afterMethod().This is done in line 15
  • Line 15 states that call afterMethod() for id aopAfterMethod
  • Similarly for beforeMethod we define in Line 16,17.

    In above example we have

    Aspect – SimpleProfiler.class
    Point-cut – aopafterMethod,aopBefore
    Advice <aop:before> <aop:after>

    Now I am ready to run my main class and class methods of FooService.

    public class Boo {
    public static void main(final String[] args) throws Exception {
    BeanFactory ctx = new ClassPathXmlApplicationContext("spring.xml");
    FooService foo = (FooService) ctx.getBean("fooService");
    foo.getFoo("Pengo", 12);
    foo.getAfter();
    foo.getBefore("Harshit");
    }
    }


    OutPut is
    After the method call ( log messagefor getAfter method )
    My name is Harshit (log message for getBefore)
    After the method call (log message for getAfter method)

    How to build various pointcut expression.

    IS Twitter the new business card?


    Recently a new trend is visible during tech-meet ups. While some people meeting up there were handing out business cards (mostly Moo Cards), the majority of people were merely adding the new faces they met directly to their Twitter follow lists via their smart phones. “Is Twitter the new business card?” This is how it went down:

    Person meets person

    Pleasantries are exchanged

    Small chit chat about common business interests

    Potential plans are made

    “Let me get your contact info”

    “Do you have Twitter?” (Note: this is where a business card should be exchanged)

    “Why, yes I do?”

    Both parties whip out Smart Phones and open respective Twitter clients

     Both parties type “follow newperson” into the Twitter client and submit

     “Great, nice to meet you. I will be in touch!”

    It’s a novel idea, really. I did it myself. I found it easy and I didn’t have to worry so much about sorting through a mess of business cards when I got home (no, I don’t use a scanner). But then I ran into a significant issue: “Who the heck was that guy? Why am I following this person? What was that lady’s name again?” While doing such a thing is certainly convenient, is it realistic if you want to build a solid business relationship. There’s no way to enter details about this person, unless of course you immediately @ message them and say “Nice to meet you re: xyz.” But what if it’s for a business deal or a job opportunity? You certainly don’t want to announce that to the world. I think there’s an interesting opportunity here for Twitter, in terms of monetizing. What if the company gave people an opportunity to save contact details about a person as they add others to their follow lists? Perhaps an add-on service that we can subscribe to in order to turn Twitter into a contact database of sorts. Or, some sort of LinkedIn integration would be swell, too.

    Post taken from : IS Twitter the new business card?

    Java Performance Tip


    Consider the case in which >, == and >= operator are used for comparison.

    long starttime = System.currentTimeMillis();
    for (int i = 0; i < 8888888; i++) {
    if (i == 10 || i < 10) {

    }
    }
    System.out.println(“Total time taken case1″+(System.currentTimeMillis()-starttime));

    starttime = System.currentTimeMillis();
    for (int i = 0; i < 8888888; i++) {
    if (i <= 10) {

    }
    }
    System.out.println(“Total time taken case2″+(System.currentTimeMillis()-starttime));

    Output is :
    Total time taken case1 31ms
    Total time taken case2 16ms

    I guess not many people fall for 1st case but still i have seen code implemented using case 1.
    Just a cautionary Tip.

    When Google Latitude Stalking Isn’t Such A Bad Thing


    Yesterday, Silicon Valley’s local CBS affiliate ran a story (video here) about a woman getting her purse snatched. But what’s interesting is the way she got it back: With an assist from Google Latitude.

    You see, in her purse, her phone had Google’s location-based social networking service installed, and it was updating the location of her phone in real-time. So even though the thief hopped in a car, when the girl called her sister, she was able to tell police exactly where the criminal was. They arrested the man and got the girl’s purse back.

    It’s worth noting that the woman said she had the service running on her phone “as a joke,” so that she and her sisters could “stalk each other.” And that’s interesting because ever since it launched a few months ago, jokes have abound about it being a tool for stalking. But at the same time, the program had a user base of over a million users just one week after it launched. People are clearly interested in using location data in social services, but it’s usually only negative connotations that are associated with stories about it. Here’s a positive one, but it still has some negative undertones.

    After all, if the girl’s sister knew exactly where the phone was, that means Google did too. Of course, Google has a policy not to share that information, but if push came to shove, and the authorities got the right warrant, Google would have to give up such information. Hopefully, you’re not a criminal — and if you are, hopefully you’re smart enough not to use Google Latitude — but it’s still a bit creepy for most people to know that a company has data about where they are at all times. And Google is hardly the only one of these services, everything from Loopt to Whrrl to Brightkite all have varying degrees of information as to your whereabouts if you use them.

    Location-based services have yet to take off on a large scale, but with Google now in the field, and major players like Facebook and MySpace undoubtedly looking at entering it, it’s only a matter of time. And when those huge social networks get into the game, there will be some initial backlash, but then people will start using it. (It may even complement other future lost purse stories.) And slowly, users will let the privacy ramifications fade into the background unless some sort of location-based horror story makes headlines.

    I, for one, welcome a future with ubiquitous location services in the social layer. Because there are upsides to location as well. This purse snatching incident is a bit extreme, but using location to find friends close by on a service like FourSquare, which I’ve been using for several weeks now, also speaks well to its potential.

    Article taken from Googl Latitude is nt such a bad thing