DataSource 接口创建只是为了有一个通用的方式来返回可以汇集等的连接?在 Java EE 中,应用程序服务器是否实现了这个接口,并且部署的应用程序是否引用了数据源而不是连接? 解决方案 更好的可扩展性和维护性对于DriverManager,您需要知道所有详细信息(主机、端口、用户名、密码、驱动程序类)才能连接到数据库并获取连接.将属性文件中的内容外部化并不会改变您需要了解它们的事实.使用 DataSource 您只需要知道 JNDI 名称.AppServer 关心细节,不是由客户端应用程序的供应商配置,而是由托管应用程序的管理员配置.可扩展性:假设您需要自己创建连接,您将如何处理不断变化的负载,有时您有 10 个用户,有时您有 1000 个,您不能在需要时就获得连接,然后释放"它以便数据库服务器不会退出连接,这会导致您进入连接池.DriverManager 不提供,DataSource 提供.如果您要自己编写连接池,则必须使用DriverManager,否则使用DataSource.I am reading the Java JDBC specification (vr. 4) and I encountred this statement:What I am trying to understand is what the difference is between a Connection and a DataSource, and why it exists. I mean, the block above says that the details about a datasource is transparent to the application, but wouldn't externalizing database properties such as username, password, url etc in a property file and then use DriverManager work in the same way?And is the DataSource interface created only to have a common way of returning connections that can be pooled etc? In Java EE, does the application server implement this interface and the applications deployed to have a reference to a datasource instead of a connection? 解决方案 Better scalability and maintenanceFor DriverManager you need to know all the details (host, port, username, password, driver class) to connect to DB and to get connections. Externalizing those in a properties file doesn't change anything about the fact that you need to know them.Using a DataSource you only need to know the JNDI name. The AppServer cares about the details and is not configured by the client application's vendor, but by an admin where the application is hosted.Scalability:Suppose you need to create connections yourself, how would you deal with changing load, sometime you have 10 users sometime you have 1000, you can't just get a connection whenever you need one and later 'release' it so the Database server does not get out of connections, which leads you to connection pooling. DriverManager does not provide it, DataSource does.If you are going to program a connection pool yourself then you have to use DriverManager, otherwise go with DataSource. 这篇关于为什么我们使用 DataSource 而不是 DriverManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!