Grails – Is my bean a singleton?

May 6, 2014 at 12:50

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:

You can see which beans are configured, and see their specifics by accessing their properties (each definition is an instance of the GenericBeanDefinition class).