Spring配置数据库连接信息

2022-10-05 11:38:45

1.直接配置数据库信息

(1)导入连接池依赖

pom.xml

<!-- 数据库连接池druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency>

(2)编写spring核心配置文件

bean6.xml

<!--    配置连接池--><beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"><propertyname="driverClassName"value="com.mysql.cj.jdbc.Driver"></property><propertyname="url"value="jdbc:mysql://localhost:3306/lin?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"></property><propertyname="username"value="root"></property><propertyname="password"value="123456"></property></bean>

2.引入外部属性文件

(1)创建properties格式的属性文件,写数据库信息

jdbc.properties

prop.driverClass=com.alibaba.druid.pool.DruidDataSource
prop.url=jdbc:mysql://localhost:3306/lin?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC
prop.username=root
prop.password=123456

(2)把外部properties引入spring配置

1.context名称空间

<?xml version="1.0" encoding="UTF8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

2.引入外部文件

bean6.xml

<!--    引入外部文件--><context:property-placeholderlocation="classpath:jdbc.properties"></context:property-placeholder><!--    配置连接池--><beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"><propertyname="driverClassName"value="${prop.driverClass}"></property><propertyname="url"value="${prop.url}"></property><propertyname="username"value="${prop.username}"></property><propertyname="password"value="${prop.password}"></property></bean>

如果有什么疑惑的地方欢迎评论区交流

  • 作者:枫叶精灵s
  • 原文链接:https://blog.csdn.net/m0_46481563/article/details/123940306
    更新时间:2022-10-05 11:38:45