Card 06/ 07

ExerciseDifficulty: Advanced1 min

Practice: Choosing a Scope for Three Beans

A repository, a receipt builder and a per-request context, and whether any of them needs a proxy.

A bean's scope, how long one instance lives and who shares it, should follow its state: shared and unchanging means singleton (one instance for the whole application), collecting data for one use means prototype (a new instance on every request for the bean), and belonging to one web request means request scope. Assign a scope to each bean below, and say whether wiring it into a singleton would need a scoped proxy, a stand-in object that forwards each call to the instance for the current request.

  1. RideRepository: stateless, talks to the database, and is used by everything.
  2. PdfReceiptBuilder: collects lines of text across several method calls while one receipt is being built, then is thrown away.
  3. CurrentRideContext: one per web request, used by a singleton RideAuditor elsewhere in the application.
See the assignments
  1. Singleton. It holds no changing per-caller data, which is the case singleton scope exists for.
  2. Prototype. It collects data for one use and is then thrown away; sharing one builder across every receipt would mix their lines together, just as two callers sharing one counter corrupt each other's totals.
  3. Request scope, with a scoped proxy. A singleton is built at startup, when no request exists, so without the proxy the application would fail to start.