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