
Originally Posted by
jsinai
This is a newbie question: I can successfully get the advice in my aspect class to fire based on my pointcuts; but the work my advice needs to do depends on access to a spring bean. Is there a pattern to follow to inject a bean into my @Aspect class? I've tried @Resource, @Autowired, ApplicationContextAware and nothing works.
Any help is appreciated.
If you don't mind mixing .aj aspect and @Aspect in your project :
Code:
package __SET_YOURS__;
import javax.annotation.Resource;
import java.lang.reflect.Field ;
import org.aspectj.lang.reflect.FieldSignature ;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContext;
public abstract aspect AbstractDependencyInjection implements ApplicationContextAware {
private ApplicationContext _ctx ;
public abstract pointcut resourceAccess();
Object around():resourceAccess(){
FieldSignature fs = (FieldSignature)thisJoinPoint.getSignature();
Field field = fs.getField();
String beanid = field.getAnnotation(Resource.class).name();
if (beanid.equals("")) {
beanid = field.getName();
}
return this._ctx.getBean(beanid) ;
}
/*
* (non-Javadoc)
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext inContext) {
this._ctx = inContext ;
}
}
Code:
package __SET_YOURS__;
import javax.annotation.Resource;
import CLASS_THAT_WILL_HAVE_RESOURCE_INJECTED;
public aspect REAL_DependencyInjection extends AbstractDependencyInjection {
public pointcut resourceAccess(): get(@Resource * *) && within(CLASS_THAT_WILL_HAVE_RESOURCE_INJECTED+) ;
}
(you can adapt pointcut definition at your criteria…)
Code:
@Aspect
public class CLASS_THAT_WILL_HAVE_RESOURCE_INJECTED {
…
@Resource(name="BEAN_ID_TO_INJECT")
protected YourInjectedBeanClass yourInjectedField = null ;
…
}
and in your applicationContext.xml
Code:
<bean class="CLASS_THAT_WILL_HAVE_RESOURCE_INJECTED" factory-method="aspectOf" />