I have a Java method, getAllItems(), and I created an aspect method, which is called after getAllItems() ends.
@Repository
@Scope("prototype")
public class ItemDao {
// not using database connection for this question; the program works fine, except aspects
public List<String> getIAllItems() {
List<String> items = new ArrayList();
items.add("item1");
return items;
}
}
The aspect class is this:
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import java.util.List;
@Aspect
public class MyAspects {
@AfterReturning(pointcut = "execution(* ro.telacad.dao.ItemDao.getIAllItems(..))", returning="items")
public void afterGetAllItems(List<String> items) {
System.out.println(items);
}
}
So, after calling getAllItems() I expect to see in console printed "[item1]", but the aspect method is not called. There is no error in console, and the application, except aspects, works fine. So I consider all the spring beans are created.
In appConfig.xml, the beans are declared like this:
<context:component-scan base-package="ro.telacad.*" />
<aop:aspectj-autoproxy/>
My question is what I did wrong for aspects.
MyAspects
is not picked up by Spring's component scanning as it does not have the @Component
annotation, and neither has @Aspect
. @Repository
does have the annotation.
Either add the @Component
annotation to MyAspects
, or explicitly declare the bean in your XML config:
<bean id="myAspects" class="com.yourpackage.MyAspects">
...
</bean>