Piotr Gabryanczyk’s Blog

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

  • Blogroll

    • I have joined Anti-IF Campaign

@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… 🙂

Advertisements

2 Responses to “@Configurable without Spring in 10 minutes”

  1. Idetrorce said

    very interesting, but I don’t agree with you
    Idetrorce

  2. Idetrorce, would you expand on what in particular do you disagree with?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: