创建一个db.properties
用于加载jdbc
jdbc.url=jdbc:mysql://localhost:3306/setcharcter?characterEncoding=utf8&serverTimezone=UTC jdbc.password=123456 jdbc.username=root jdbc.driver=com.mysql.jdbc.Driver
创建spring配置文件
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd " default-autowire="byName" > <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="password" value="${jdbc.password}"></property> <property name="username" value="${jdbc.username}"></property> </bean> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mapper"></property> <!-- 当使用自动注入的时候 优先级比较高
会先创建对象,在加载配置文件,这样的话配置文件的信息就取不到了
所以要使用这个,不然会加载不到properties文件的属性值 --> <property name="sqlSessionFactoryBeanName" value="factory"></property> </bean> </beans>