I'm using Spring AOP and therefore indirectly CGLIB in my Spring MVC controller. Since CGLIB needs an default constructor I included one and my controller now looks like this:
@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
}
}
The problem now is, that IntelliJ IDEA's static code analysis reports a potential NullPointerException, because this.exampleService
might be null.
My question is:
How to prevent these false positive null pointer warnings? One solution would be to add assert this.exampleService != null
or maybe use Guava's Preconditions.checkNotNull(this.exampleService)
.
However, this has to be added to each method for each and every field used in this method. I would prefer a solution I could add in a single place. Maybe a annotation on the default constructor or something?
EDIT:
Seems to be fixed with Spring 4, however I'm currently using Spring 3: http://blog.codeleak.pl/2014/07/spring-4-cglib-based-proxy-classes-with-no-default-ctor.html
You can annotate your field (if you are sure that it will really not be null) with:
//import org.jetbrains.annotations.NotNull;
@NotNull
private final ExampleService exampleService;
This will instruct Idea to assume this field to be not-null in all cases. In this case your real constructor will also be annotated automatically by Idea:
public ExampleController(@NotNull ExampleService exampleService){
this.exampleService = exampleService;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With