First8 staat voor vakmanschap. Al onze collega’s zijn een groot aanhanger van Open Source en in het bijzonder het Java-platform. Wij zijn gespecialiseerd in het pragmatisch ontwikkelen van bedrijfskritische Java toepassingen waarbij integratie van systemen, hoge eisen aan beveiliging en veel transacties een belangrijke rol spelen. Op deze pagina vind je onze blogs.

Grails Expert Tip #8 – There’s a Bean for That

Recently I code reviewed some of the Grails (2.4.5) code of another team (of course ūüôā ) and here’s a snippet I came across.

In some “search helper service”:

grails-logo-smThis team somehow needed some ‘generic’ way of counting the amount of records in the database, I thought.

First questions which popped up were: what can be put in the passed collection? Why the elaborate way of getting the current Hibernate Session? Why and how is createFilter used here? I had some initial code review comments about this particular piece of code.

Inject beans, don’t look em up

In non-static contexts¬†there’s¬†no need to get the singleton GrailsApplication¬†through the Holders¬†class with¬†the static method¬†getGrailsApplication(). You can always inject grailsApplication in another Spring bean (e.g. controller or service). “Holder” classes, such as grails.utils.Holders and¬†org.springframework.web.context.request.RequestContextHolder,¬†usually expose stuff through static methods which can be¬†conveniently called from almost any location – which at the same time are consequently¬†over-used by¬†most beginning developers.

Use the beans already available

Next to that, there’s usually no need to get the current Hibernate Session through Spring’s ApplicationContext using¬†grailsApplication.mainContext. Grails shipped with the Hibernate plugin, which already exposes some beans such as

Just inject sessionFactory in your service. [code language=”groovy” gutter=”false”]


If you’re wondering what¬†the deal is with¬†the¬†session.createFilter construction – I’ll get back on that¬†ūüėČ

Original post