1.管理数据源
第一步:pom文件导入坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
</dependencies>
第二步:写一个spring_datasource.xml文件配置bean
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="abc123"></property>
</bean>
这个bean的配置要注意的是driverClaName不要写成了driver,写jdbc习惯的人会这样
第三步:测试类,打印连接地址
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.sql.SQLException;
public class DataSourceText {
public static void main(String[] args) throws SQLException {
ApplicationContext ioc=new ClassPathXmlApplicationContext("spring_datasourec.xml");
DataSource dataSource = ioc.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}
}
2.引入外部文件
针对这个管理数据源的程序,其实我们可以写一个properties文件,把数据库连接的信息放进去
这里我建了一个jdbc.properties文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=abc123
接下来就是如何引入外部文件了,这个我们上面那个spring_datasource.xml文件里面配置一个bean,但是连接信息写死了,我们就动态获取吧,分为两步,第一:把这个properties文件引入进去,用到text约束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--引入外部属性文件 加context约束-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
注意看上面的命名空间多了个context就是因为导入了context约束来导入这个文件