Tim*_*the 10 java static-analysis intellij-idea spring-aop cglib
我正在使用Spring AOP,因此在我的Spring MVC控制器中间接使用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
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,IntelliJ IDEA的静态代码分析报告了一个潜在的NullPointerException,因为它this.exampleService可能为null.
我的问题是:
如何防止这些误报空指针警告?一种解决方案是添加assert this.exampleService != null或使用番石榴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的
您可以使用以下方式注释您的字段(如果您确定它确实不为空):
//import org.jetbrains.annotations.NotNull;
@NotNull
private final ExampleService exampleService;
Run Code Online (Sandbox Code Playgroud)
这将指示 Idea 在所有情况下假定该字段不为空。在这种情况下,你真正的构造函数也将被 Idea 自动注释:
public ExampleController(@NotNull ExampleService exampleService){
this.exampleService = exampleService;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
454 次 |
| 最近记录: |