Access to Application Context from Grails Filter Constructor
How can I access the Application Context from a Grails Filter. I am able to do so from a Controller by using the following:
def ctx = ApplicationHolder.application.mainContext
But in a开发者_StackOverflow社区 Filter ctx is null.
In this case, I'm specifically trying to access the application context in the Filter's constructor.
You shouldn't use the holder classes - they're deprecated in 2.0 and will be removed in a future release.
The best way to access the application context from a controller, filter, service, etc. is to add a dependency injection for the GrailsApplication, i.e
def grailsApplication
Then you can get the context via
def ctx = grailsApplication.mainContext
It's unusual to do work in a constructor that's related to Spring beans, so if possible you should refactor. Grails artifacts are Spring beans, so they're instantiated while the application context is being constructed.
Controllers are a bit different since they're not singletons like most beans, so by the time they get constructed (one per request) the holders are populated. But in general you should avoid doing GORM work, accessing the application context, etc. in a constructor since it's unlikely that things are wired up yet.
精彩评论