【发布时间】:2016-02-09 10:24:03
【问题描述】:
我在我的 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 可能为空。
我的问题是:
如何防止这些误报空指针警告?一种解决方案是添加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
【问题讨论】:
-
该构造函数实际上必须是可调用的,还是必须存在?你能从中抛出一个异常吗?
-
一种选择是在编译时或运行时使用 AspectJ weaver,而不是 cglib。 Spring 文档解释了如何做到这一点。这种方法的一个好处是它允许依赖注入和检测通常是“贫血”的域对象。另一个是支持将使用接口检测的类,因此使用动态代理而不是 cglib - 取决于类的性质,这可能是一个好习惯。
-
当存在
setter的exampleService时问题仍然存在吗?
标签: java intellij-idea spring-aop static-analysis cglib