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

前端之家收集整理的这篇文章主要介绍了java – 如何防止假阳性空指针警告,当使用CGLIB / Spring AOP?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 Spring MVC控制器中使用Spring AOP,因此间接地使用CGLIB.由于CGLIB需要一个默认构造函数,所以我包括一个,我的控制器现在看起来像这样:
  1. @Controller
  2. public class ExampleController {
  3.  
  4. private final ExampleService exampleService;
  5.  
  6. public ExampleController(){
  7. this.exampleService = null;
  8. }
  9.  
  10. @Autowired
  11. public ExampleController(ExampleService exampleService){
  12. this.exampleService = exampleService;
  13. }
  14.  
  15. @Transactional
  16. @ResponseBody
  17. @RequestMapping(value = "/example/foo")
  18. public ExampleResponse profilePicture(){
  19. return this.exampleService.foo(); // IntelliJ reports potential NPE here
  20. }
  21. }

现在的问题是,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)与:
  1. //import org.jetbrains.annotations.NotNull;
  2. @NotNull
  3. private final ExampleService exampleService;

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

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

猜你在找的Java相关文章