在spring中自动将空列表转换为null

时间:2012-08-16 16:53:15

标签: spring collections aop nullable

我希望我的所有DAO方法都返回一个空集合而不是null。我怎么能用AOP弹簧做到这一点?

1 个答案:

答案 0 :(得分: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/>