package com.clq.spring.junit;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(locations = "classpath:bean.xml")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testUpdate() {
String sql = "INSERT INTO t_emp VALUES(NULL,?,?,?)";
int rows = jdbcTemplate.update(sql,"林平之", 20, "未知");
System.out.println(rows);
}
}
<?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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--引入外部属性文件创建数据源的对象-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driver" value="${jdbc.driver}"/>
<property name="name" value="${jdbc.name}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置 JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="druidDataSource"/>
</bean>
</beans>
连接数据库的文件
jdbc.name=root
jdbc.password=3333
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
报错:
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@78d39a69 testClass = com.clq.spring.junit.JdbcTemplateTest, locations = ["classpath:bean.xml"], classes = [], contextInitializerClasses = [], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = [], contextCustomizers = [], contextLoader = org.springframework.test.context.support.DelegatingSmartContextLoader, parent = null]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'druidDataSource' defined in class path resource [bean.xml]: Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver'; Cannot convert value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver': no matching editors or conversion strategy found