Where to store a DataSource resource in a Java web app?
This is a rookie question. What's the best place to put
@Resource
private DataSource ds;
in a web application? Do I put it in a servlet, context listener or maybe there开发者_运维技巧's a better place for it? Also, do I create a new Connection object in my doGet()/doPost() or should I do it somewhere else? What's the best practice for stuff like this? Thank you!
What's the best place to put
@Resource DataSource
in a web application? Do I put it in a servlet, context listener or maybe there's a better place for it?
In the very same class where you'd like to call DataSource#getConnection()
.
Also, do I create a new Connection object in my doGet()/doPost() or should I do it somewhere else?
You usually do that in a method of a DAO class where you'd like to interact with the DB, in a try
block where you close the Connection
(and Statement
and ResultSet
, if any) in the finally
block.
In a more abstracted and flexible setup, you could also do DataSource#getConnection()
in a DAO manager class or a transaction manager class.
精彩评论