前言:很久之前学习 SSM 框架的时候,大部分都是通过 xml 文件来进行集成,最近复习的时候发现通过 xml 文件来集成比较繁琐,于是综合了网上资料通过注解的方式重新集成学习了一遍。
pom 文件先贴上来
<!--Spring核心基础依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- SpringMVC 、Spring 的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- Spring-jdbc 的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- servlet 依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
</dependency>
<!--mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- Mybatis 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- Mybatis 结合 Spring 的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--mybatis generator-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- c3p0 连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.1</version>
</dependency>
<!-- 整合jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
一、注入 mybatis
1、新建 jdbc.properties 文件,内容就是自己的数据库连接信息,这个我就不贴出来了
2、新建 SpringConfig 文件,内容如下
package com.wxw.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import sun.rmi.runtime.Log;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.logging.Logger;
//表明它是一个配置类
@Configuration
//引用jdbc配置文件
@PropertySource("classpath:jdbc.properties")
public class MybatisConfig{
/**
* 使用 c3p0 连接池初始化数据源配置,定义了数据库连接的相关配置
* @return
* @throws Exception
*/
@Bean
public DataSource getDataSource(
@Value("${driver}") String driver,
@Value("${url}") String url,
@Value("${user}") String user,
@Value("${password}") String password
) throws Exception {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setDriverClass(driver);
return comboPooledDataSource;
}
/**
* mybatis 注入数据源,配置 xml 文件扫描路径
* 基于连接获取了Mybatis中的关键对象sqlSessionFactory
* @param comboPooledDataSource
* @return
* @throws IOException
*/
@Bean("sqlSessionFactory")
public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource comboPooledDataSource) throws IOException {
//注入配置好的数据源
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(comboPooledDataSource);
//配置mybatis xml 的扫描路径为 resources 下的mapper 目录
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = patternResolver.getResources("classpath:mapper/*.xml");
sqlSessionFactoryBean.setMapperLocations(resources);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
// 扫描mapper包的扫描器,mapper包中用于存放数据持久层的接口,而扫描器扫描后,可以生成这个接口相对应的bean对象,不需要我们再调用getMapper()方法手动获取
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.wxw.mapper");
// 配置 mybatis 的 sqlSessionFactory
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
二、引入 spring mvc 相关内容
1、新建 ServletConfig 文件,添加以下内容
package com.wxw.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//表明它是一个配置类
@Configuration
//表示扫描这个包下的所有组件,即包含有类似@Controller,@Configuration,@Bean等注解的部分
@ComponentScan("com.wxw")
//表示启用WebMvc的相关注解和默认配置。
@EnableWebMvc
//这个类继承了WebMvcConfigurerAdapter,从名字可以看出这是一个关于WebMvc配置的类,可以通过重写父类方法的方式为当前项目进行配置。
public class ServletConfig extends WebMvcConfigurerAdapter{
// 加载了一个视图解析器,视图文件的路径是/WEB-INF/pages,文件的类型是.html文件。此外这个类中还可以通过重写addInterceptors()方法添加拦截器
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/pages/", ".html");
}
}
三、将 mybatis 及 spring MVC 放入此加载类中
1、新建 WebInitializer 文件,添加以下内容
package com.wxw.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
//服务器启动时,spring会通过这个类(spring-web 这个jar中的 org.springframework.web.SpringServletContainerInitializer)
// 中的onStartup()方法加载WebApplicationInitializer这个接口及其子类,那么我们只需要写一个类实现这个接口,
// 再把我们需要启动时加载的部分放在这个类中就可以了
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// 加载 spring、mybatis 相关内容,MybatisConfig.class 为之前添加 Mybatis 的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{MybatisConfig.class};
}
// 加载springMvc 相关内容,ServletConfig.class 为之前添加 spring MVC 的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{ServletConfig.class};
}
// 配置 controller 接口方法访问路径后缀
@Override
protected String[] getServletMappings() {
return new String[] {"*.do"};
}
}
四、测试 SSM 整合
1、使用 mybatis generator 自动生成 entity、mapper、xml 相关文件
pom 文件 标签中加入此插件
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
新建 generatorConfig.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry location="D:\Developer\MavenRepository\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar" />
<context id="context1">
<jdbcConnection connectionURL="" driverClass="com.mysql.jdbc.Driver" password="" userId="" />
<!--实体类-->
<javaModelGenerator targetPackage="com.wxw.entity" targetProject="D:\MyLearn\spring01\src\main\java\com\wxw\entity" />
<!--xml-->
<sqlMapGenerator targetPackage="mapper" targetProject="D:\MyLearn\spring01\src\main\resources\mapper" />
<!--mapper-->
<javaClientGenerator targetPackage="com.wxw.mapper" targetProject="D:\MyLearn\spring01\src\main\java\com\wxw\mapper" type="XMLMAPPER" />
<!--schema 数据库名-->
<table schema="zm_scm" tableName="sys_user" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="false" ></table>
</context>
</generatorConfiguration>
然后通过 maven
2、新增 controller、service、serviceImpl
serviceImpl
@Service
public class SysUserServiceImpl implements SysUserService{
@Autowired
SysUserMapper sysUserMapper;
@Override
public List<SysUser> selectList() {
return sysUserMapper.selectList();
}
}
service
public interface SysUserService {
List<SysUser> selectList();
}
controller
@RestController
@RequestMapping("/sysUser")
public class SysUserController {
@Autowired
SysUserService sysUserService;
@RequestMapping("selectByUserList.do")
public List<SysUser> selectList(){
return sysUserService.selectList();
}
}
启动项目后,访问
http://localhost:8080/sysUser/selectByUserList.do