我在
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; }