当前位置: 动力学知识库 > 问答 > 编程问答 >

Spring MVC controller initialization code

问题描述:

I have a spring MVC project, in one of the controllers, i have a DB connection object that needs to be initialized only once in the controller, what is the best approach to follow when adding this initialization code, for now, i used a static block in the controller where i added the initialization code, do u have any other suggestions.

thanks in advance

网友答案:

Make it a Spring bean. That way it's a singleton (by default), and can be injected wherever you want.

Note that even if you leave its initialization in the controller, making it static is useless, since a controller is also a Spring bean, which is a singleton by default.

网友答案:

Well in spring you don't need to initialize the db connections yourself , It provide support for db connections

You just need to specify the the bean in .xml files and directly autowired that bean into your controller

use dao pattern to implement database connections see some example it will be easy container will manage db connections object life cycle for you

Thanks, Himanshu

网友答案:

May I recommend you read the Spring reference guide for Object Relational Mapping and Data Access? Its quite comprehensive and details how to set up a data source, session factory, implement DAO classes, transaction management etc... Hopefully you will find this is a good place to start.

分享给朋友:
您可能感兴趣的文章:
随机阅读: