|
From: <jas...@ma...> - 2004-12-10 13:52:25
|
On 5 Dec 2004, at 20:56, Colin Sampaleanu wrote: > I'm thinking of the best strategy for making the locale available to > the MessageSourceAccessor, as per SPR-485: > http://opensource.atlassian.com/projects/spring/browse/SPR-485 > This would probably be a TheadLocal that the locale is bound to. The > question is what the best strategy to do this is. I FWIW I used exactly this mechanism lately on a project using Tapestry & Spring & Hibernate; it lets any locale specific code anywhere in your code base just work without complex wiring of locale-holding interfaces all over the code. Our main use case was that the entity model contains i18n text so depending on the local of the current thread, reference data is automatically translated on views etc. e.g. on a Currency or Location object, the getName() method will return the translated name for the current thread when its used in a template. Ditto for most of the rest of the reference data in the system and formatting of all numbers/dates/currencies. The Tapestry engine (or dispatch servlet in springs case) then just sets up the thread local on each request, and all the locale specific code just works like a charm. This leads to a really neat, almost invisible i18n mechanism throughout the code without excessive wiring. If you ever really need to explicitly pass in a Locale to some code, you can - but by default you can use the thread local approach. Whilst it often feels like a static ThreadLocal is a bit of a hack, for something like Locale it seems a neat & simple solution. > suppose DispatcherServlet could just bind the locale to a > threadlocal, using the configured LocaleResolver, before dispatching. > The problem here is that it won't pick up a changed locale as a result > of a setLocale call on the localeresolver by the web code. > Alternately, a ControllerInterceptor would have the same limitation, > and would also have to be configured in front of every controller. > What I am thinking would perhaps work though is something like a new > Interface called LocaleAccessor. The implementation would be a > JavaBean, and would be bound to the thread by the dispatcher. What it > would hold would be both the Servlet Request, and also the > LocaleResolver. When asked to get the Locale, it would be able to use > the normal localeresolver, since it would also have the request. > > The whole point of this is so that non-view layer code can have access > to locale resolution, in a similar fashion to view layer code. > > Can anybody think of a better mechanism? No - I prefer the thread local approach; works like a charm. The fact that the locales are immutable & intern'd objects with no lifecycle also kinda helps too :). For most other things, I'd recommend avoiding ThreadLocals :) James ------- http://radio.weblogs.com/0112098/ |