加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何防止假阳性空指针警告,当使用CGLIB / Spring AOP?

发布时间:2020-12-14 16:34:28 所属栏目:Java 来源:网络整理
导读:我在 Spring MVC控制器中使用Spring AOP,因此间接地使用CGLIB.由于CGLIB需要一个默认构造函数,所以我包括一个,我的控制器现在看起来像这样: @Controllerpublic class ExampleController { private final ExampleService exampleService; public ExampleCont
我在 Spring MVC控制器中使用Spring AOP,因此间接地使用CGLIB.由于CGLIB需要一个默认构造函数,所以我包括一个,我的控制器现在看起来像这样:
@Controller
public class ExampleController {

    private final ExampleService exampleService;

    public ExampleController(){
        this.exampleService = null;
    }

    @Autowired
    public ExampleController(ExampleService exampleService){
        this.exampleService = exampleService;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/example/foo")
    public ExampleResponse profilePicture(){
        return this.exampleService.foo(); // IntelliJ reports potential NPE here
    }
}

现在的问题是,IntelliJ IDEA的静态代码分析报告了潜在的NullPointerException,因为this.exampleService可能为null.

我的问题是:

如何防止这些假阳性空指针警告?一个解决方案是添加assert this.exampleService!= null或者可能使用Guava的Preconditions.checkNotNull(this.exampleService).

但是,必须将此功能添加到此方法中使用的每个字段的每个方法中.我宁愿在一个地方添加一个解决方案.可能是默认构造函数或某事的注释?

编辑:

似乎要用Spring 4修复,但是我正在使用Spring 3:
http://blog.codeleak.pl/2014/07/spring-4-cglib-based-proxy-classes-with-no-default-ctor.html

解决方法

您可以注释您的字段(如果您确定它真的不为null)与:
//import org.jetbrains.annotations.NotNull;
@NotNull
private final ExampleService exampleService;

这将指示Idea在所有情况下假定此字段不为null.在这种情况下,您的真实构造函数也将被Idea自动注释:

public ExampleController(@NotNull ExampleService exampleService){
    this.exampleService = exampleService;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读