【问题标题】:Default field value with springSecurityServicespringSecurityService 的默认字段值
【发布时间】:2014-06-19 06:26:43
【问题描述】:

我确定我以前见过这个,但我现在找不到任何关于它的信息。当我尝试这样做时:

class Foo {

    def springSecurityService
    User userInstance = springSecurityService.currentUser

}

我在编译结束时收到以下错误:

无法在空对象上获取属性“currentUser”

我可以不设置服务的默认用户吗?

  • 运行 Grails 2.2.0。
  • Foo 是一个域类。

编辑

我使用javax.annotations.PostConstruct 尝试了以下解决方案,但从未调用过带注释的方法。我认为它没有被调用,因为我在其中放入了 println 语句,它没有被调用。我正在用new Foo() 实例化我的课程。

【问题讨论】:

    标签: grails spring-security


    【解决方案1】:

    试试这个

    import javax.annotation.PostConstruct
    
    class Foo {
    
        def springSecurityService
        User userInstance
    
        @PostConstruct
        private void init() {
            userInstance = springSecurityService.currentUser
        }
    }
    

    您的代码不起作用的原因是您试图在springSecurityService 被依赖注入之前设置userInstance

    我假设Foo 是一个域类,如果它是src/groovy 中的一个类,那么这种方法将不起作用,因为这些类不受依赖注入的影响。

    【讨论】:

    • 是的,它是一个域类。我刚刚得出的结论是依赖注入还没有发生,并且不确定最好的解决方法是什么。谢谢!
    • 嗯。好吧,我没有收到编译错误,但永远不会调用 init() :|
    • @CharlesWood 既然你总是可以从springSecurityService 访问它,为什么你还需要将当前用户存储在一个字段中?
    • 因为Foo 被持久化了,我希望数据库记住当前用户是谁以供以后参考,就像域类中的任何字段一样。
    猜你喜欢
    • 2014-05-21
    • 2022-01-02
    • 1970-01-01
    • 2017-04-04
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    相关资源
    最近更新 更多