? 如果xml文件不在原本存在的 resources 文件中
applicationContext2.xml
<?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="demo2/com/DoubleW2w/resources/db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="usersDao" class="demo2.com.DoubleW2w.dao.impl.UsersDaoImpl">
<constructor-arg index="0" ref="jdbcTemplate"/>
</bean>
<bean id="usersService" class="demo2.com.DoubleW2w.service.impl.UsersServiceImpl">
<constructor-arg name="usersDao" ref="usersDao"/>
</bean>
</beans>
db.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/bjsxt1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
jdbc.username = root
jdbc.password = 123456
测试类
public class TestDemo2 {
private static final Logger logger = LoggerFactory.getLogger(TestDemo2.class);
private ApplicationContext applicationContext;
@Before
public void beforeTest(){
applicationContext = new ClassPathXmlApplicationContext("demo2/com/DoubleW2w/resources/applicationContext2.xml");
}
@Test
public void testInsertUsers(){
UsersService usersService = (UsersService)applicationContext.getBean("usersService");
Users users = new Users();
users.setUsername("suibian");
users.setUsersex("female");
logger.info(Integer.toString(usersService.addUsers(users)));
}
}
其他数据源的配置
c3p0数据源
<context:property-placeholder location="properties文件位置"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
jdbc里面的数据源
<context:property-placeholder location="properties文件位置"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
总结:
- Druid的数据源配置中,数据库驱动是
name="driverClassName" ,而不是 name = "driverClass"
如果文章对你有帮助的话,记得点赞关注哦
|