Wednesday, May 18, 2011

Spring AOP

Hey...

Today I’m going to discuss about Spring AOP. Aspect Oriented Programming is a concept that completes Objective Oriented Programming. In OOP we should solve our problems in Classes methods using some design patterns strategy. But 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. (Such concerns are often termed crosscutting concerns in AOP literature.) On the other hands, by using aspects, we will be able to assign some features to the classes and methods.

AOP Concept
Let us begin by defining some central AOP concepts and terminology. These terms are not Spring-specific... unfortunately, AOP terminology is not particularly intuitive; however, it would be even more confusing if Spring used its own terminology.
  • 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 Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
  • 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.
  • 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.) Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join 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.
  • 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.
  • Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
Types of advice:
  • Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  • After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  • After throwing advice: Advice to be executed if a method exits by throwing an exception.
  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
Around advice is the most general kind of advice. Since Spring AOP, like AspectJ, provides a full range of advice types, we recommend that you use the least powerful advice type that can implement the required behavior. For example, if you need only to update a cache with the return value of a method, you are better off implementing an after returning advice than an around advice, although an around advice can accomplish the same thing. Using the most specific advice type provides a simpler programming model with less potential for errors. For example, you do not need to invoke the proceed() method on the JoinPoint used for around advice, and hence cannot fail to invoke it.

In Spring 2.0, all advice parameters are statically typed, so that you work with advice parameters of the appropriate type (the type of the return value from a method execution for example) rather than Object arrays.

The concept of join points, matched by pointcuts, is the key to AOP which distinguishes it from older technologies offering only interception. Pointcuts enable advice to be targeted independently of the Object-Oriented hierarchy. For example, an around advice providing declarative transaction management can be applied to a set of methods spanning multiple objects (such as all business operations in the service layer).

Abstract Example
Let us take an abstract example. Suppose that we should implement a bank account class. This class has two major methods: withdraw and deposit. This can be such Implementation:
public class BankAccount {
    Long account;

    public Long getAccount() {
        return account;
    }

    public Boolean withdraw(Long withdrawAmount) {
        if (withdrawAmount < account) {
            account -= withdrawAmount;
            return true;
        } else {
            return false;
        }
    }

    public void deposit(Long depositAmount) {
        account += depositAmount;
    }
}
This is the core of accounting. But we should have some feature among it. For example only the user with role of "power-user" has withdraw and deposit accessibility or during withdraw and deposit method we should log each operation. So the class will be change to this:
public class BankAccount {
    Long account;

    public Long getAccount() {
        return account;
    }

    public Boolean withdraw(Long withdrawAmount) {
        log.Log("withdraw method is started");
        if (SecurityContext.getCurrentUser().hasRole("power-user")) {
            if (withdrawAmount < account) {
                account -= withdrawAmount;
                return true;
            } else {
                return false;
            }
        } else {
            throw new Exception("You don't have this accessiblity");
        }
    }

    public void deposit(Long depositAmount) {
        log.Log("deposit method is started");
        if (SecurityContext.getCurrentUser().hasRole("power-user")) {
            account += depositAmount;
        } else {
            throw new Exception("You don't have this accessiblity");
        }
    }
}
whenever any change request or new feature arrives from customer, we should change the class or create some other classes then call them within this class. But this problem has other solution in AOP. The core of our system is BankAccount class. We can implement it regardless of other things and test it with JUnit to prevent from some unforeseen bugs. Then we should an aspect to handle security and logging strategy.
public class BankAccount {
    Long account;

    public Long getAccount() {
        return account;
    }

    public Boolean withdraw(Long withdrawAmount) {
        if (withdrawAmount < account) {
            account -= withdrawAmount;
            return true;
        } else {
            return false;
        }
    }

    public void deposit(Long depositAmount) {
        account += depositAmount;
    }
}
@Aspect
public class BankAccountSupervisor {
    @Pointcut("execution(* BankAccount.*(..))")
    public void logingPoint() {
    }

    @Pointcut("execution(* BankAccount.withdraw(..)) ||
execution(* BankAccount.deposit(..))")
    public void withdrawDepositPoint() {
    }

    @Around("logingPoint()")
    public Object loging(ProceedingJoinPoint pjp) throws Throwable {
        beforRunningMethodLog(pjp);
        Object returnVal = pjp.proceed();
        return returnVal;
    }

    @Around("withdrawDepositPoint()")
    public Object withdrawing(ProceedingJoinPoint pjp) throws Throwable {
        if (SecurityContext.getCurrentUser().hasRole("power-user")) {
            Object returnVal = pjp.proceed();
            return returnVal;
        } else {
            throw new Exception("You don't have this accessiblity");
        }
    }

    private void beforRunningMethodLog(ProceedingJoinPoint pjp) {
        System.out.println("just befor running '" + pjp.getSignature().getName() + "' method of '" + pjp.getTarget().getClass().getName() + "' class.");
    }
}
Enabling @AspectJ Support
To use @AspectJ aspects in a Spring configuration you need to enable Spring support for configuring Spring AOP based on @AspectJ aspects, and autoproxying beans based on whether or not they are advised by those aspects. By autoproxying we mean that if Spring determines that a bean is advised by one or more aspects, it will automatically generate a proxy for that bean to intercept method invocations and ensure that advice is executed as needed.
The @AspectJ support is enabled by including the following element inside your spring configuration:
<aop:aspectj-autoproxy/>
Declaring a pointcut
Recall that pointcuts determine join points of interest, and thus enable us to control when advice executes. Spring AOP only supports method execution join points for Spring beans, so you can think of a pointcut as matching the execution of methods on Spring beans. A pointcut declaration has two parts: a signature comprising a name and any parameters, and a pointcut expression that determines exactly which method executions we are interested in. In the @AspectJ annotation-style of AOP, a pointcut signature is provided by a regular method definition, and the pointcut expression is indicated using the @Pointcut annotation (the method serving as the pointcut signature must have a void return type).

An example will help make this distinction between a pointcut signature and a pointcut expression clear. The following example defines a pointcut named 'anyOldTransfer' that will match the execution of any method named 'transfer':
@Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature
The pointcut expression that forms the value of the @Pointcut annotation is a regular AspectJ 5 pointcut expression. For a full discussion of AspectJ's pointcut language, see the AspectJ Programming Guide (and for Java 5 based extensions, the AspectJ 5 Developers Notebook) or one of the books on AspectJ such as “Eclipse AspectJ” by Colyer et. al. or “AspectJ in Action” by Ramnivas Laddad.
Supported Pointcut Designators
Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions:
  • execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP
  • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
  • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
  • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type
  • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
  • @target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type
  • @args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)
  • @within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)
  • @annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation
Combining pointcut expressions
Pointcut expressions can be combined using '&&', '||' and '!'. It is also possible to refer to pointcut expressions by name. The following example shows three pointcut expressions: anyPublicOperation (which matches if a method execution join point represents the execution of any public method); inTrading (which matches if a method execution is in the trading module), and tradingOperation (which matches if a method execution represents any public method in the trading module).
@Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}

@Pointcut("within(com.xyz.someapp.trading..*)")
private void inTrading() {}
    

@Pointcut("anyPublicOperation() && inTrading()")
private void tradingOperation() {}
It is a best practice to build more complex pointcut expressions out of smaller named components as shown above. When referring to pointcuts by name, normal Java visibility rules apply (you can see private pointcuts in the same type, protected pointcuts in the hierarchy, public pointcuts anywhere and so on). Visibility does not affect pointcut matching.
Example
I had a post about file repository. Here I'm going to extend the sample of that post example. I will log everything happens in Controller, Service and Dao layers and the time that each method spends. I also should check security for user list use case. The users with role of "power_user" or "administrator" can save or update the user and just the user with role of "administrator" can delete the user. OK. Let's start step by step:

1. Add aspectjweaver.jar
Add aspectjweaver.jar jar file to you project lib directory.
2. spring-servlet.xml
Spring AOP is implemented in pure Java. There is no need for a special compilation process. Spring AOP does not need to control the class loader hierarchy, and is thus suitable for use in a J2EE web container or application server. So in spring context we should just place "<aop:aspectj-autoproxy/>" tag. This will enable the use of the @AspectJ style of Spring AOP.
<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--security config-->
    <import resource="classpath:security-config.xml"/>

    <context:component-scan base-package="com"/>

    <aop:aspectj-autoproxy/>

    <!--Tiles 2-->
    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/layout/tiles-config.xml</value>
            </list>
        </property>
    </bean>

    <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
        <property name="order" value="1"/>
    </bean>

    <!--hibernate-->
    <import resource="classpath:hibernate-config.xml"/>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="100000000"></property>
    </bean>

</beans>
3. Implementation of LoggingSupervisor class
It is an aspect. Here we are going to log every things and time spending. Take a look to the code:
package com.aspects;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
 

@Component
@Aspect
public class LoggingSupervisor {
    @Pointcut("execution(* com.ucs..*.*(..))")
    public void logingPoint() {
    }

    @Around("logingPoint()")
    public Object loging(ProceedingJoinPoint pjp) throws Throwable {
        beforRunningMethodLog(pjp);
        Long startTime = System.currentTimeMillis();
        Object returnVal = pjp.proceed();
        Long endTime = System.currentTimeMillis();
        timeSpendingLog(pjp, endTime - startTime);
        return returnVal;
    }

    private void beforRunningMethodLog(ProceedingJoinPoint pjp){
        System.out.println("just befor running '" + pjp.getSignature().getName() + "' method of '" + pjp.getTarget().getClass().getName() + "' class.");
    }
    private void timeSpendingLog(ProceedingJoinPoint pjp, Long spendingTime){
        System.out.println("running '" + pjp.getSignature().getName() + "' method of '" + pjp.getTarget().getClass().getName() + "' class takes " + spendingTime + "miliseconds.");
    }
}
as I mentioned i should enable this logging for any methods in controllers, service and dao layers. So I should do that in pointcut expression(the red line). In Around advice I will log the method name and class name just before running the method and then save the current time as startTime. After running the method (blue line) I will save the current time again as endTime. Then I will log the subtraction of these two time as method spending time.
4. Implementation of UserSupervisor class
Here I should check the security. I use spring security so the security and current user information are in spring security context. In last version of this project I checked the role via spring security annotation:
@Service
public class UserServiceImpl implements UserService {
...


    @PreAuthorize("hasRole('administrator') or hasRole('power_user')")
    public void saveOrUpdate(User user, List<Long> roleIds) {
        List<Role> roleList = new ArrayList();
        for (Long roleId : roleIds) {
            roleList.add(findRoleById(roleId));
        }
        user.setRoleList(roleList);

        user.setPassword(encodePassword(user.getPassword()));
        roleDao.saveOrUpdate(user);
    }
 

    @PreAuthorize("hasRole('administrator')")
    public void deleteAll(Long[] ids) {
        List<User> userList = new ArrayList();
        for (Long id : ids) {
            userList.add(roleDao.findById(id));
        }
        roleDao.deleteAll(userList);
    }

...
}
But here I commented the red line to assign the responsibly to the UserSupervisor aspect. Take a look to the class:
package com.aspects;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
 

@Component
@Aspect
public class UserSupervisor {
    @Pointcut("execution(* com.ucs.user.service.UserService.saveOrUpdate(..))")
    public void userSavePoint() {
    }

    @Pointcut("execution(* com.ucs.user.service.UserService.deleteAll(..))")
    public void userDeletePoint() {
    }

    @Around("userSavePoint()")
    public Object checkSecurity4Save(ProceedingJoinPoint pjp) throws Throwable {
        if (hasRole("power_user") || hasRole("administrator")) {
            return pjp.proceed();
        } else {
            throw new Exception("You Don't have save or update accessibility");
        }
    }

    @Around("userDeletePoint()")
    public Object checkSecurity4Delete(ProceedingJoinPoint pjp) throws Throwable {
        if (hasRole("administrator")) {
            return pjp.proceed();
        } else {
            throw new Exception("You Don't have delete accessibility");
        }
    }

    private UserDetails getCurrentUserDetail() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = null;
        if (principal instanceof UserDetails) {
            userDetails = (UserDetails) principal;
        }
        return userDetails;
    }

    private Boolean hasRole(String roleName) {
        Collection<GrantedAuthority> grantedAuthorityList = getCurrentUserDetail().getAuthorities();
        for (GrantedAuthority grantedAuthority : grantedAuthorityList) {
            if (grantedAuthority.getAuthority().equals(roleName)) {
                return true;
            }
        }
        return false;
    }
}
Here I should determine exactly the method of the class in pointcut expression(Blue lines). Then I should check the security just before running the method(Red lines) in advice methods. If the current user does not have specified role, an exception will be thrown.
5. Results
If you go to file repository list page, for example, You will have this results:
just befor running 'fileList' method of 'com.ucs.file.FileController' class.
just befor running 'findAllFiles' method of 'com.ucs.file.service.FileServiceImpl' class.
just befor running 'findAllFiles' method of 'com.ucs.file.dao.FileDaoImpl' class.
Hibernate: select this_.id as id7_2_, this_.is_file as is2_7_2_, this_.file as file7_2_, this_.name as name7_2_, this_.owner_id as owner6_7_2_, this_.parent_file_id as parent5_7_2_, user2_.id as id9_0_, user2_.account_non_expired as account2_9_0_, user2_.account_non_locked as account3_9_0_, user2_.credentials_non_expired as credenti4_9_0_, user2_.enabled as enabled9_0_, user2_.name as name9_0_, user2_.password as password9_0_, user2_.username as username9_0_, file3_.id as id7_1_, file3_.is_file as is2_7_1_, file3_.file as file7_1_, file3_.name as name7_1_, file3_.owner_id as owner6_7_1_, file3_.parent_file_id as parent5_7_1_ from tb_file this_ left outer join tb_user user2_ on this_.owner_id=user2_.id left outer join tb_file file3_ on this_.parent_file_id=file3_.id where this_.owner_id=? and this_.parent_file_id is null order by this_.is_file asc, this_.id desc
Hibernate: select rolelist0_.user_id as user1_1_, rolelist0_.role_id as role2_1_, role1_.id as id8_0_, role1_.authority as authority8_0_ from tb_user_role rolelist0_ left outer join tb_role role1_ on rolelist0_.role_id=role1_.id where rolelist0_.user_id=?
running 'findAllFiles' method of 'com.ucs.file.dao.FileDaoImpl' class takes 65miliseconds.
running 'findAllFiles' method of 'com.ucs.file.service.FileServiceImpl' class takes 65miliseconds.
just befor running 'findAllFilesSize' method of 'com.ucs.file.service.FileServiceImpl' class.
just befor running 'findAllFilesSize' method of 'com.ucs.file.dao.FileDaoImpl' class.
Hibernate: select count(this_.id) as y0_ from tb_file this_ where this_.owner_id=? and this_.parent_file_id is null
running 'findAllFilesSize' method of 'com.ucs.file.dao.FileDaoImpl' class takes 22miliseconds.
running 'findAllFilesSize' method of 'com.ucs.file.service.FileServiceImpl' class takes 22miliseconds.
running 'fileList' method of 'com.ucs.file.FileController' class takes 292miliseconds.
And also if you login as user with "user" role, in user save operation, you will have an exception with this title:"You Don't have save or update accessibility". To test this operation, First login as a user with "user role" then refer to user list page. Then view a record. In record view page, click edit button. Then click the save button in record edit page. Here you will find exception.
Source Code
It's the time to download the source code and try it yourselves.The application needed jar files are the same as this example. So you can copy all of them to here: [app-root]/lib/
The application database script is available in [app-root]/db/filerepository.sql. you can restore it in your mysql server. the connection datasource properties is in [app-root]/src/database.properites. And after you deploy the project in you application server (like tomcat) the home page will be: http://localhost:8080/home/view.html
the admin user specification is:
username: administrator
password: 123456
you can use it to log in for the first time.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

1 comment:

Unknown said...

nice example plus explanation ...