2

我想让我所有的 DAO 方法返回一个空集合而不是 null。我怎样才能用 AOP spring 做到这一点?

4

1 回答 1

6

这应该有效:

@Aspect
@Service
public class DaoAspect {

    @Around("execution(java.util.List com.example.*Dao.get*())")
    public Object aroundGetDaoMethods(ProceedingJoinPoint joinPoint) throws Throwable {
        final Object retVal = joinPoint.proceed();
        return retVal != null ? retVal : Collections.emptyList();
    }

}

调整切入点以仅匹配您希望拦截的方法。您还需要添加 AspectJ JAR:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.6.6</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.6</version>
</dependency>

并启用 CLASSPATH 扫描:

<aop:aspectj-autoproxy/>
于 2012-08-16T17:18:24.800 回答