Friday, January 27, 2012

Targeting all methods in a class - Spring AOP


Annotations are a great way to tag methods that should be targeted by an aspect.  This allows the user of your aspect to apply its functionality wherever the developer wishes; rather than having to hard code a point cut expression.  This is easy enough to do:
@annotation(com.example.Annotation)
But, what if you want to target all methods in a class marked with an annotation?   Well, that expression is a little more complicated.  Let me show you how.
execution(* (@com.example.Annotation *).*(..))
To explain this, let’s take a look at format of execution():
execution([[returnType] ([classQualifiers] [className]).[methodName]([arguments]))
We want to target any class marked with @Annotation.  So, we indicated that by placing @Annotation right before the className (in this case * for all classes).  When you think of it, this just mirrors Java syntax; the class annotations are listed before the class name.  What makes this look mucky is that we need to wrap the class pattern in parenthesis so our implementation knows that we expect the annotation to be attached to the class, not the method.
The above expression only targets classes marked with @Annotation.  If you want to also target classes that extend classes marked with @Annotation, we need to add the + modifier to the class pattern (which indicated class X or subclasses of X):
execution([[returnType] [className]+.[methodName]([arguments]))
But, because of precedence issues, we need to introduce another set of parenthesis.  The final expression looks like this:
execution(* ((@com.example.Annotation *)+).*(..))

Thursday, January 5, 2012

Great article on building an early phase startup

Using Log4j conversion patterns


A brief note on conversion patterns used in log4j:
log4j.appender.stdout.layout.ConversionPattern=%-5p %d [%t] %c: %m%n
The pattern is defined as follows:
1) %-5p refers to the type of log entry. This would appear in the log file as INFO, DEBUG, ERROR, etc. -5 is there to include the word in a 5-character width column.
2) %d refers to the date.
3) %t does not refer to the time but to the name of the thread that raised this log entry. In the example above, this code is enclosed in square brackets which are used in the log entry.
4) %c lists the category that generated this log which usually is the class name.
5) %m displays the message
6) %n adds a carriage return.