Grails - Is my bean a singleton?
At an interesting discussion about how to bulk-delete objects in Grails, I suggested using the sessionFactory bean to explicitly flush the session when required.
One of the participants was concerned about the sessionFactory not being a singleton, in which case injecting it in a controller or service (or any other bean for that matter) would be very expensive as a new instance would be created each time.
I was pretty sure that bean would be a singleton... why wouldn't it be, when even in the SessionFactory documentation is said that "Usually an application has a single SessionFactory instance"? And being Grails a convention over configuration framework, the normal thing to do would be to follow that convetion :-) .
But still, he had a point: being pretty sure about something doesn't make it true :) . I couldn't find documentation on how the session factory is configured (an old topic in Grails: where are the Spring and Hibernate specifics documented?), but luckily, is very easy to access that information at runtime:
def grailsApplication // Injected by default in controllers, accessible as a regular bean elsewhere
assert grailsApplication.mainContext.getBeanDefinition('sessionFactory') instanceof org.springframework.beans.factory.support.GenericBeanDefinition
// Have I any non-singleton bean ?
grailsApplication.mainContext.getBeanDefinitionNames().any {
!grailsApplication.mainContext.getBeanDefinition(it).singleton
}
You can see which beans are configured, and see their specifics by accessing their properties (each definition is an instance of the GenericBeanDefinition class).

0 comentarios
Se conservan los comentarios originales. No se admiten nuevos comentarios.