Reputation: 6989
I am having trouble injecting a property into LoggingAspect
class. Imaging I have an AspectJ class:
@Aspect
public class LoggingAspect {
private IBoc theBo;
/** getter and setter **/
}
This is the BOC:
public interface IBoc {
}
public class BocImpl implements IBoc {
}
and the Spring configuration for BOC:
<beans ...>
<aop:aspectj-autoproxy/>
<bean id="theBoc" class="org.huahsin.BocImpl"/>
</beans>
In applicationContext.xml file, I configure the AspectJ in this way:
<beans...>
<bean id="theLog" class="org.huahsin.LoggingAspect">
<property name="theBo" ref="theBoc"/>
</bean>
</beans>
How could I inject theBo
in LoggingAspect
class?
Update on 17 Oct 2012
I found some clue here. If I remove the <aop:aspectj-autoproxy>
, the member variable theBo
in class LoggingAspect
will not be null. If I have that code, theBo will be null.
Upvotes: 1
Views: 1704
Reputation: 23413
Normally Spring
is responsible for both creating and configuring beans. AspectJ
aspects, however, are created by the AspectJ
runtime. You need Spring
to configure the aspect that AspectJ
has created. For the most common case of singleton aspects such as yours LoggingAspect
aspect above, AspectJ
defines an aspectOf()
method that returns the aspect instance. You can tell Spring
to use the aspectOf()
method as a factory method for obtaining the aspect instance.
For e.g.:
<beans>
<bean name="loggingAspect"
class="org.huahsin.LoggingAspect"
factory-method="aspectOf">
<property name="theBo" ref="theBoc"/>
</bean>
<bean id="theBoc" class="org.huahsin.BocImpl"/>
</beans>
UPDATE:
Define factory method in your class:
@Aspect
public class LoggingAspect {
private IBoc iBoc;
private static LoggingAspect instance = new LoggingAspect();
public static LoggingAspect aspectOf() {
return instance;
}
public void setiBoc(IBoc iBoc) {
this.iBoc = iBoc;
}
}
Upvotes: 3