2016-11-08 38 views
0

在下面的控制器代码片段中,当试图访问springSecurityService.currentUser时,我得到一个空指针异常。我希望def springSecurityService自动注入服务,我错过了什么?注入springSecurityService不起作用

@Transactional(readOnly = true) 
@Secured('ROLE_USER') 
class TaskController { 

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"] 

    def index(Integer max) { 
     params.max = Math.min(max ?: 10, 100) 
def springSecurityService 
def user = springSecurityService.currentUser 

回答

5

将其他Spring Bean注入到控制器或服务中是在类级完成的,而不是在方法内完成的。

例如,你的代码应该是这样的:

@Transactional(readOnly = true) 
@Secured('ROLE_USER') 
class TaskController { 

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"] 
    def springSecurityService // inject the bean here, at the class level 

    def index(Integer max) { 
     params.max = Math.min(max ?: 10, 100) 
     def user = springSecurityService.currentUser