简述: 最近在学习Spring的时候发现了需要写很多配置文件,每次写练手项目的时候就很难受,到处没有模板,故写此文章来记录。
本文初发于 “曾晨de小站” zengchen233.cn,同步转载于此。
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
spring-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="数据库用户名"/>
<property name="password" value="数据库密码"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:cn/zengchen233/dao/*.xml"/>
</bean>
</beans>
applicationContext.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:aop="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">
</beans>
自动装配Bean需要用到这个注解<aop:component-scan base-package="cn.zengchen233"/>
然后在类中配置@Component
,这个注解可以在后面增加括号指定Bean的名称 @Component("名称")
注意注意!必须要开启注解,要不然不管用的。
还有自动装配需要这个注解<context:annotation-config/>
有的时候在类中用到了其他类,这个时候有很懒不想去配置xml配置文件,这个时候通过@Autowired
自动装配方式,从IoC
容器中去查找到,并返回给该属性,很棒!