Java Reference
In-Depth Information
following listing). It only needs to provide the declared initialization method and
setters for any injected properties.
Listing 3.6 InventoryPopulator fills the database when the bundle starts
public class InventoryPopulater {
private Inventory inventory;
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public void populate() {
boolean isInventoryPopulated = (inventory.getFoodCount() > 0);
if (!isInventoryPopulated) {
inventory.createFood("Blue cheese", 3.45, 10);
inventory.createFood("Wensleydale cheese", 1.81, 15);
inventory.createFood("Normal chocolates", 6.99, 8);
Check if
there's
food
before
making
more
}
B
}
}
The populate method adds two cheeses and a chocolate to the database. To avoid try-
ing to persist the same blue cheese row six times, the populater is defensive and only
creates new foods if the database is empty B .
WARNING: HOW MANY TIMES IS AN EAGER BLUEPRINT BEAN INITIALIZED? The
eager Blueprint runs once when its bundle is started. Be careful here—this
feels a lot like constructing and initializing a Java singleton, but it's not the
same. A singleton will be initialized once in the lifetime of a JVM . Bundles, on
the other hand, can be stopped and started repeatedly without restarting the
JVM . This means each eager Blueprint bean will be created the same number
of times that the bundle is started during the lifetime of the virtual machine.
Be careful using init methods to change the external state. We're patently
using the init method as a simple way to change the external state here, so
this is a case of “do as we say, not do as we do!”
3.2.3
Making use of the data
Now that Fancy Foods has a datasource and a JPA persistence bundle, all that's
needed is something to take advantage of the persistence. The special offer in sec-
tion 2.3.3 used the time of year to determine which chocolates should be on offer.
Many other foods, on the other hand, aren't seasonal purchases. Instead, shops aim
to promote foods that are selling poorly, so that they don't get left with piles of food
that are past their sell-by dates. The container-managed persistence makes that kind
of promotion simple.
Let's add a second department, in charge of cheese. The appeal of cheese doesn't
vary seasonally, but cheese does have a limited lifespan, so it's important to keep the
Search WWH ::




Custom Search