2

我有一个 Java 方法 getAllItems(),并创建了一个方面方法,该方法在 getAllItems() 结束后调用。

@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;
    }
}

方面类是这样的:

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);
    }
}

因此,在调用 getAllItems() 之后,我希望在控制台中看到打印的“[item1]”,但不会调用方面方法。控制台没有错误,应用程序(除了方面)工作正常。所以我认为所有的spring bean都被创建了。

在 appConfig.xml 中,bean 的声明如下:

<context:component-scan base-package="ro.telacad.*" />
<aop:aspectj-autoproxy/>

我的问题是我在方面做错了什么。

4

1 回答 1

2

MyAspects没有被 Spring 的组件扫描拾取,因为它没有@Component注释,也没有@Aspect. @Repository确实有注释。

@Component将注释添加到MyAspects,或在 XML 配置中显式声明 bean:

<bean id="myAspects" class="com.yourpackage.MyAspects">
...
</bean>
于 2019-10-20T10:01:58.570 回答