springSecurityService is null in base controller
This is a rather weird problem and I been at it for a while so I am going nuts.
I have a controller extending another controller so I can have multiple controllers inheriting a method and they go something like this:
class EventController extends EventAwareController {
def springSecurityService
def edit = {
// this line prints out principal id
println springSecurityService.principal.id
def eventInstance = getAuthorizedEventById(params.id)
if (!eventInstance) {
flash.message = "${message(code: 'event.not.found.message')}"
redirect(action: "list", controller: "event")
return false
}
}
class EventAwareController {
def eventService
def springSecurityService
def getAuthorizedEventById(def eventId) {
def event
if (eventId) {
// this springSecurityService is null and throws an error
event = eventService.findAuthorizedEvent(eventId, springSecurityService.principal.id)
if (event) {
session.eventId = eventId
}
}
return event
}
}
EventAwareController is throwing:
java.lang.NullPointerException: Cannot get property 'principal' on null object at com.ticketbranch.EventAwareController.getAuthorizedEventById(EventAwareController.groovy:14)
but my prinln statement in EventContro开发者_JS百科ller prints principal id without any issues?!? So springSecurityService is injected as null in EventAwareController?
Any ideas? suggestions? Thanks.
You have the field in both classes, and this is a problem when using Groovy. Dependency injection in Grails is typically done like you're doing, with def <beanname>
. This is a public field, so Groovy creates a public getter and setter for it and makes the field private. The getter isn't used, but Spring sees the setter and since beans are configured to be wired by name (as opposed to by type) the bean is injected since there's a match between the setter name (setSpringSecurityService
) and the bean name.
Since you have this twice, you have two setters and one wins, so you'll have a null value for the private field in one class.
But like any public (or protected) property the dependency injection is inherited, so just remove it from all of your subclasses and leave it in the base class.
精彩评论