1:创建Spring配置文件spring-datasource,IOC容器管理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="Ht1971350878" ></property>
</bean>
测试类:
@Test
public void testDataSource() throws SQLException {
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
System.out.println(dataSource.getConnection());
}
2:也可以引入jdbc.properties配置文件,之后可以通过${key}的方式访问value
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=Ht1971350878
<!--引入jdbc.properties,之后可以通过${key}的方式访问value-->
<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>
测试类:
@Test
public void testDataSource() throws SQLException {
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
System.out.println(dataSource.getConnection());
}
结果效果也是一样的