2016-11-08 75 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