![a244598c9aa55dc96dd294ae1a87563d.png](https://i-blog.csdnimg.cn/blog_migrate/2a90f313a4daec13947b15b670b6f59a.jpeg)
1、在web项目中加载spring容器(基于xml的配置)
配置在web.xml中配置监听器,代码如下:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
此时启动web容器(tomcat),将会报错,没有找到spring的配置文件
Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
解决方案就是在WEB-INF下建立applicationContext.xml文件,并且加入以下内容才能成功启动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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
">
</beans>
这样就可以在web容器中初始化spring容器,但是此时没有做任何事情。
如果不想在WEB-INF下添加spring的配置文件,或者不想使用applicationContext.xml这个名称,需要在web.xml中指明文件位置。这里声明contextConfigLocation这个上下文参数,指定文件路径为类路径下的bean.xml文件夹(也就是在src的根目录下)。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:bean.xml</param-value>
</context-param>
2、在web项目中使用Spiring Mvc(基于xml的配置)
以下图是spring mvc所经历所有过程
![c4f41804b55095a467b86b894a96f82f.png](https://i-blog.csdnimg.cn/blog_migrate/7658b360bfdc46606c8688a47332225f.jpeg)
2.1 由上图知首先需要一个Dispatcher Servlet的分发器
2.1.1 在web.xml中配置如下代码
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.2.2 使用sevlet3.0的特性配置servlet,加载spring mvc的配置文件
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("初始化spring mvc");
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/demo-servlet.xml");
ServletRegistration.Dynamic registration =
servletContext.addServlet("app", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
此时启动web容器(tomcat),将会报错,没有找到spring mvc的配置文件
Could not open ServletContext resource [/WEB-INF/demo-servlet.xml]
2.2 根据需求,在WEB-INF下创建demo-servlet.xml文件
这个xml文件就相当于Hander Mapping,包含这url和controller之间的映射关系。这里将路径/welcome和com.wangyang.ssm.control.Welcome类中的方法进行映射
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="/welcome" class="com.wangyang.ssm.control.Welcome"/>
</beans>
2.3 编写controller
在controller中处理模型数据(这里打印了welcome)以及返回模型的名称welcome。
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Welcome extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(
HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
System.out.println("welcome");
return new ModelAndView("welcome");
}
}
2.4 配置视图解析器
在demo-servlet.xml中加入如下代码。将controller返回的视图名称welcome,使用jsp解析器将模型传递给相应的jsp页面。
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
此时启动web容器即可正常使用
以上采用xml的方式配置spring和spring mvc。接下里采用annotation的方式进行配置
3、在web项目中加载spring容器和spring mvc(基于annotation的方式)
采用Servlet3.0的特性,初始化spring mvc 的DispatcherServlet和spring的监听器
public class SpringWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
spring的java配置类
@Configuration
public class RootConfig {
}
spring mvc的java配置类
@Configuration
@ComponentScan("com.wangyang.ssm.control")
public class WebConfig {
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
}
4、Spring集成mybatis
4.1 加入需要的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
4.2 在spring的配置文件beans.xml中添加mybatis的配置(基于xml的配置)
<!--配置bean的扫描目录-->
<context:component-scan base-package="com.wangyang.ssm"/>
<!--配置数据源-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置mybatis的sqlSessionfactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置mybatis的事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.wangyang.ssm.model.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
classpath:jdbc.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tssm?serverTimezone=GMT
jdbc.username=root
jdbc.password=123456
com.wangyang.ssm.model.UserMapper内容如下:
public interface UserMapper {
@Select("select * from t_user where id = #{id}")
User selByUser( int id);
}
4.3 使用java类来进行mybatis的配置
@Configuration
public class RootConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
System.out.println("----------sqlSessionfactory------------");
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean;
}
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/tssm?serverTimezone=GMT");
dataSource.setUsername("root");
dataSource.setPassword("123456");
return dataSource;
}
@Bean
public MapperFactoryBean userMapper() throws Exception {
MapperFactoryBean factoryBean = new MapperFactoryBean();
factoryBean.setMapperInterface(UserMapper.class);
factoryBean.setSqlSessionFactory(sqlSessionFactory().getObject());
return factoryBean;
}
}
5、spring集成mybatis后的两种使用方式
方式一:基于Dao接口和实现类的
1、导入maven依赖
2、创建mybatis的映射文件和实体类
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="group">
<select id="selByGroup" resultType="com.wangyang.ssm.model.Group">
select * from t_group where id = 1
</select>
<insert id="addGroup">
insert into t_group (name)
values (#{name})
</insert>
</mapper>
实体类
public class Group {
private int id;
private String name;
......
}
3、编写dao接口和实现类
public interface IGroupDao {
void add(Group group);
Group load(int id);
}
这里血药继承SqlSessionDaoSupport,此时就具有了SqlSession,但是在配置GroupDao的bean时要注入SqlSessionFactory
public class GroupDao extends SqlSessionDaoSupport implements IGroupDao {
@Override
public void add(Group group) {
getSqlSession();
}
@Override
public Group load(int id) {
Group group = (Group)getSqlSession().selectOne("group.selByGroup", Group.class);
return group;
}
}
4、持久层的配置
<?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:mybatis="http://mybatis.org/schema/mybatis-spring"
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://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd">
<!--1、配置数据源-->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--2、配置mybatis的sqlSessionfactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--数据库连接池-->
<property name="dataSource" ref="dataSource" />
<!--mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
<!--<property name="mapperLocations" value="classpath*:com/wangyang/ssm/mapper/**/*.xml"/>-->
<!--<property name="transactionFactory">-->
<!--<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />-->
<!--</property>-->
</bean>
<!--3、创建Dao对象注入SqlSessionFactory-->
<bean id="groupDao" class="com.wangyang.ssm.dao.GroupDao">
<property name="SqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
5、测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/applicationContext*.xml")
public class TestSpringMyabatis {
@Autowired
IGroupDao groupDao;
@Test
public void testGroup(){
System.out.println(groupDao.load(1));
}
}
方式二:基于动态代理mapper
只需要开启接口的扫描
<?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:mybatis="http://mybatis.org/schema/mybatis-spring"
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://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd">
<!--1、配置数据源-->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--2、配置mybatis的sqlSessionfactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--数据库连接池-->
<property name="dataSource" ref="dataSource" />
<!--mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
<!--<property name="mapperLocations" value="classpath*:com/wangyang/ssm/mapper/**/*.xml"/>-->
<!--<property name="transactionFactory">-->
<!--<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />-->
<!--</property>-->
</bean>
<!--发现映射器-->
<mybatis:scan base-package="com.wangyang.ssm.mapper" />
</beans>
com.wangyang.ssm.mapper的内容如下:
public interface UserMapper {
User selByUser(int id);
void addUser(User user);
}
注意:这里要求namespace为接口的名称
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wangyang.ssm.mapper.UserMapper">
<select id="selByUser" resultType="com.wangyang.ssm.model.User">
select * from t_user where id = 1
</select>
<insert id="addUser">
insert into t_user (username,password)
values (#{username},#{password})
</insert>
</mapper>
6、应该注意的问题
在观察xml中的配置会发现如下问题:
![7f48652dd76aeb8571e956ebc769ffeb.png](https://i-blog.csdnimg.cn/blog_migrate/86eb6d1325e910f28b049e0a8f15d74d.jpeg)
这是由于,SqlSessionFactoryBean 实现了 Spring 的 FactoryBean 接口(请参考 Spring 文档的 3.8 章节)这就说明了由 Spring 最终创建的 bean 不是 SqlSessionFactoryBean 本身。而是工厂类的 getObject()返回的方法的结果。这种情况下,Spring 将会在应用启动时为你创建 SqlSessionFactory 对象,然后将它以 SqlSessionFactory 为名来存储。
![a4a857d33df3c2743ff8008fd03a8ee4.png](https://i-blog.csdnimg.cn/blog_migrate/48a72f386c02162a701a444522c33dca.jpeg)