Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

Archive for the ‘aspectj’ Category

Aspect Oriented Programming – real life examples

Posted by Piotr Gabryanczyk on April 1, 2008

Some time ago, on my previous blog, I wrote a short series of articles showing real live examples of using AOP. It is time to group them together and share with you again:

Enjoy!

Posted in aop, aspectj, java, programming, spring | Leave a Comment »

@Configurable without Spring in 10 minutes

Posted by Piotr Gabryanczyk on December 1, 2006

Why

I was asked recently to remove Spring from my project… I know, I know one step forward two steps back… I wasn’t happy at all. It was because Eclipse was crashing when two plugins had its own copy of spring library… Good excuse to remove Spring…

Problem

We are heavily using @Configurable and AspectJ so we needed some mechanism which could replace spring aspect in injecting dependencies.

How

Just look below:

 1 @Aspect()
 2 public class ConfigurableHackAspect {
 3     private static Map<String, Object> beanMap = new HashMap<String, Object>();
 4 
 5     public static void registerBean(String id, Object bean){
 6         beanMap.put(id, bean);
 7     }
 8 
 9     @After("@within(com.xyz.common.ConfigurableHack) && execution(*.new(..))")
10     public void afterConstructor(JoinPoint jp){
11         for(Field f : getAllFields(jp)){
12             if (f.isAnnotationPresent(InjectDependency.class) && beanMap.containsKey( f.getName())){
13                 try {
14                     f.set(jp.getTarget(), beanMap.get(f.getName()));
15                 } catch (IllegalAccessException e) {
16                     throw new RuntimeException(e);
17                 }
18             }
19         }
20     }
21 
22     private Field[] getAllFields(JoinPoint jp) {
23      return jp.getTarget().getClass().getFields();
24     }
25 }

Example usage

 1 class XYZ{
 2      3     @InjectDependency public IMarketDataSupplier marketDataSupplier;
 4      5 }
 6 

Summary

It is not perfect as it requires injected field to be public, but it does the job and is good enough for 10 minutes… 🙂

Posted in annotations, aop, aspectj, java, spring, Uncategorized | 2 Comments »