在以下来自 Controller 的代码片段中,当尝试访问springSecurityService.currentUser时,我得到了一个空指针异常。我希望def springSecurityService自动注入(inject)服务,我想念什么?

@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

最佳答案

将其他Spring bean注入(inject)到 Controller 或服务中是在类级别而不是在方法内部完成的。

例如,您的代码应如下所示:

@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

关于grails - 注入(inject)springSecurityService不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40478347/

10-10 04:45