开发者

Where to store a DataSource resource in a Java web app?

开发者 https://www.devze.com 2022-12-30 11:04 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消