Charles Wood
Charles Wood

Reputation: 882

Default field value with springSecurityService

I'm sure I've seen this before, but I can't find anything about it now. When I attempt to do this:

class Foo {

    def springSecurityService
    User userInstance = springSecurityService.currentUser

}

I get the following error towards the end of compilation:

Cannot get property 'currentUser' on null object

Can I not set the default user with a service?

EDIT

I tried the below solution with javax.annotations.PostConstruct, but the annotated method is never called. I don't think it's being called because I put a println statement in it, which doesn't get called. I'm instantiating my class with new Foo().

Upvotes: 1

Views: 146

Answers (1)

Dónal
Dónal

Reputation: 187499

Try this instead

import javax.annotation.PostConstruct

class Foo {

    def springSecurityService
    User userInstance

    @PostConstruct
    private void init() {
        userInstance = springSecurityService.currentUser
    }
}

The reason your code doesn't work is because you're trying to set userInstance before springSecurityService has been dependency-injected.

I'm assuming Foo is a domain class, if it's a class in src/groovy then this approach won't work, because these classes are not subject to dependency-injection.

Upvotes: 2

Related Questions