Java Reference
In-Depth Information
Recall that the addBid method in listing 3.1 inserted the new bid submitted by the user.
The method created a java.sql.Statement from an open JDBC connection and used
the statement to insert a record into the BIDS table. The JDBC connection object used to
create the statement is a classic heavy-duty resource. It's expensive to open and should be
shared across calls whenever possible. Because it can hold a number of native resources,
it's important to close when it's no longer needed.
In listing 3.1 , the JDBC data source from which the connection is created is injected using
the @Resource annotation. We'll explore injecting resources using the @Resource an-
notation in chapter 5 ; for now, this is all that you need to know. Let's take a close look at
how you use the callbacks in listing 3.1 .
PostConstruct callback
After injecting all of the resources, the container scans the bean class for methods annotated
with @PostConstruct . If there are any methods, the methods are invoked before the
bean instance is ready for use. In this case, you mark the initialize method in listing 3.1
with the @PostConstruct annotation:
@PostConstruct
public void initialize () {
...
connection = dataSource.getConnection();
...
}
In the initialize method, you create a java.sql.Connection from the injected data
source and save it into the connection instance variable used in addBid each time the cli-
ent method is invoked.
PreDestroy callback
At some point the container decides that your bean should be destroyed. The PreDes-
troy callback gives the bean a chance to cleanly tear down bean resources before this is
done. In the cleanup method marked with the @PreDestroy annotation in listing 3.1 , you
tear down the open database connection resource before the container retires your bean:
@PreDestroy
public void cleanup() {
...
Search WWH ::




Custom Search