Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent false positive null pointer warnings, when using CGLIB / Spring AOP?

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

like image 499
Tim Büthe Avatar asked Feb 09 '16 10:02

Tim Büthe


1 Answers

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;
}
like image 188
Gergely Bacso Avatar answered Sep 27 '22 18:09

Gergely Bacso