spring - spring中null自动转为空列表

标签 spring collections aop nullable

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

最佳答案

这应该有效:

@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/>

关于spring - spring中null自动转为空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11991973/

相关文章:

java - AspectJ 切入点不适用于带有 Element.TYPE 的注释,例如 @Component

java - Spring 对 <context :component-scan/> vs <mvc:annotation-driven> 给出的@Controller 的支持

java - Spring MVC - Rest API 是将实体放在一起的最佳位置

collections - 添加来自不同实例的集合

java - 从具有不同排序标准的树集中获取元素的有效方法

Java:如何将 List<T> 中的对象添加到 Map(键:Enum,值 List<T>)

java - JPA Hibernate 通过合并进行插入而不是更新

c++ - 如何在不修改源文件的情况下修改 Pre-Build 中的源文件?

java - 如何在 Spring Boot 中以编程方式创建 bean?

java - Spring Boot 应用程序未启动