Search code examples
spring-bootspring-securityspring-boot-security

NullPointerException in autowired datasource after adding method level security annotation


I have a class using an autowired datasource. After I added a @PreAuthorize("hasRole") annotation to one of the methods in the class, the application throws a NPE when using the datasource for the first time.

java.lang.NullPointerException: Cannot invoke "javax.sql.DataSource.getConnection()" because "this.dataSource" is null

@RestController
@RequestMapping("/Parent")

public class ParentController {
    
    private static final Log log = LogFactory.getLog(ParentController.class);
    
    @Autowired DataSource dataSource;
    @Autowired UserManager userManager;
    @Autowired EmailService mailService;

    @PreAuthorize("hasRole('COORDINATOR')")
    @PostMapping("/create")
    private String createParent(final Parent inParent, HttpServletResponse response) {   

If I remove the @PreAuthorize annotation, everything works, no NPE. Not sure what I am doing wrong here.


Solution

  • When using @PreAuthorize or other means that require Spring AOP make sure you don't place them on private or final methods. Those methods won't be proxied and thus will be invoked on the proxied object (which will not have the dependencies injected).

    This is a problem in this case as the request handling method is being called directly and thus invoked on the proxy instead of the wrapped object.

    To fix make the method public instead of private.

    More information is in this blogpost written by me (as you aren't the first and probably not the last to run into this).