Mar 5, 2010 0
Spring Custom Scopes: Site Scope HOWTO
Ok, so I’ve finally got round to putting some sample code together on Site Scope with Spring Custom Scopes. I’ve been wanting to do this for some time… Sample code on Github
What does Site Scope do?
Say you are running a multi-tenant web app. E.g. you have one video rental webapp that runs 3 different web sites: netflix.com, blockbuster.com, and betamaxrules.com. For each site you sometimes want to use different beans in your spring application context.
Say for Netflix you want the page titles to be formatted with a “- Netflix” suffix, and for Blockbuster you want the page titles to be formatted with a “Blockbuster presents: ” prefix.
To solve this you can create a TitleFormatter class, and create two subclasses of it, NetflixTitleFormatter and BlockbusterTitleFormatter (I’d normally make a more flexible TitleFormatter with prefix and suffix attributes rather than subclassing, but subclassing simplifies the example).
Your app determines the current site by the domain name (or some other request/session attribute if you prefer) and our Site Scope uses the correct TitleFormatter bean for the site.
Site Scope prevents site.isXxx() code smells in your views. If you have a lot of tenants, you can end up with views looking like this:
if (site.isNetflix()) pageTitle + " - Netflix" else if (site.isBlockbuster()) "Blockbuster presents: " + pageTitle else if (site.isBetamaxRules()) pageTitle else if (site.isVhsOldSchoolRentals()) "VHS Old School Rentals have static titles"
With SiteScope this could be replaced with:
titleFormatter.format(pageTitle)
For the sample code source/HOWTO see spring-site-scope on github.
Are you going to use Site Scope? What are you going to use it for? Please share in the comments.