2011-09-30 69 views
4

这是一个相当奇怪的问题,我一直在这里一段时间,所以我疯了。springSecurityService在基本控制器中为空

我有延伸的另一控制器,所以我可以有多个控制器继承的方法和他们去这样的控制器:

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抛出:

显示java.lang.NullPointerException:无法在 空对象上获得属性'委托人' com.ticketbranch.EventAwareController.getAuthorizedEventById(EventAwareController.groovy:14)

但我在EventController中的prinln语句打印主体ID没有任何问题?!?所以springSecurityService在EventAwareController中被注入为null?

任何想法?建议?谢谢。

回答

7

您在这两个类中都有这个字段,这在使用Groovy时是个问题。 Grails中的依赖注入通常按照您的操作完成,其中def <beanname>。这是一个公共领域,因此Groovy为它创建了一个公共getter和setter,并使该字段保密。 getter没有被使用,但Spring看到setter,并且由于bean被配置为按名称连接(而不是按类型),因为设置者名称(setSpringSecurityService)和bean名称之间存在匹配,所以注入bean。

既然你有这两次,你有两个setters和一个胜,所以你将有一个类的私人领域的空值。

但是就像任何公共(或受保护的)属性一样,依赖注入是继承的,所以只需从所有的子类中移除它并将其留在基类中。

+0

很合理,谢谢。 – Micor

+0

非常酷的答案,我花了一个小时试图了解到底发生了什么......谢谢你帮助我理解发生了什么:) –