Defining constructors for AspectJ aspects.

I have read just about every tutorial and gone through several books on AspectJ and never saw more then a couple of sentences on constructors for aspects. I am working on code that generates aspects and need to initialize several properties inside the constructor.

Below is an example for logging exceptions along with a constructor for the aspect.

package aspects.exceptions;

public aspect ExceptionLoggingAspect {

	//Aspect attributes can be created like in a regular class.
	public HashMap<String, String> properties;
	//Aspect constructor
	//The constructor cannot take any arguments and cannot 
	//throw any checked exceptions!
	public ExceptionLoggingAspect(){
		//You can initialize attributes and such here
	//Pointcut for intercepting exceptions
	pointcut exceptionHandler(Exception e): 
		handler(Exception+) && args(e);
	//Pointcut for defining calls to .toUpperCase
	pointcut upperCall(): call(* *.toUpperCase(..));
	//Advice for exceptionHandler
	//This will be executed for any exception in the entire application
    before (Exception e): exceptionHandler(e) {
        System.err.println("Caught by aspect: " + e.toString());
		+ " " + thisJoinPoint.getSourceLocation() + "  FILE: " + 
		thisJoinPoint.getSourceLocation().getFileName() + "   LINE: " +
    //Advice for above pointcut "upperCall" 
    //Surrounds the function execution in a try/catch and catches any exceptions
    //This is useful so that you don't have to put exception coding in your classes
    Object around() : upperCall(){
    	catch (Exception e){
    		System.err.println("Caught by aspect: " + e.toString());
    	return null;
	declare error : call(public * java.sql.Statement+.execute*(String, ..)) : 
		"You are making a call to a Dynamic SQL LIbrary!!! Can result in SQL injection!!!";


Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *