相关 Jar 包
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
web.xml 配置
配置 DispatcherServlet 并设置启动加载
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-config.xml
配置 MyBatis、数据源、MapperSanner
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--配置 MyBatis-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--mybatis 配置文件-->
<property name="configLocation"
value="classpath:mybatis-config.xml" />
<!--mapper.xml 存放位置-->
<property name="mapperLocations"
value="classpath:mapper/*.xml" />
</bean>
<!--配置数据源-->
<!--读取 db.properties-->
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName"
value="${mysql.driver}" />
<property name="url"
value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</bean>
<!--配置 MapperScanner-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory" />
<!--@Mapper 扫描包-->
<property name="basePackage" value="cade.mapper" />
</bean>
<!--配置 component 扫描-->
<context:component-scan
base-package="cade.controller" />
<context:component-scan
base-package="cade.service" />
<!--配置 mvc 注解支持-->
<mvc:annotation-driven />
<!--配置静态资源映射-->
<mvc:resources mapping="/static/**" location="classpath:static/" />
</beans>
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>
<!--别名配置-->
<typeAliases>
<package name="cade.entity" />
</typeAliases>
</configuration>
UserMapper
@Mapper
public interface UserMapper {
List<User> listUsersAll();
}
<mapper namespace="cade.mapper.UserMapper">
<select id="listUsersAll" resultType="user">
select * from user
</select>
</mapper>
UserService
@Service
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
@Autowired
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public List<User> listUsersAll() {
return userMapper.listUsersAll();
}
}
UserController
@Controller
public class HelloController {
private final UserService userService;
@Autowired
public HelloController(UserService userService) {
this.userService = userService;
}
@ResponseBody
@RequestMapping("/users")
public List<User> listUsersAll() {
return userService.listUsersAll();
}
}
实体类
public class User {
String name;
Integer age;
// ...
}
访问 /users 进行测试
[{"name":"李四","age":20},{"name":"张三","age":23},{"name":"王五","age":23}]
配置类代替 web.xml
在 Servlet 3.0 环境下,Servlet 容器会在 classpath 下搜索实现了 javax.servlet.ServletContainerInitializer 接口的任何类,找到之后用它来初始化 Servlet 容器
Spring 实现了以上接口,实现类叫做 SpringServletContainerInitializer, 它会依次搜寻实现了 WebApplicationInitializer的任何类,并委派这个类实现配置
之后,Spring 3.2 开始引入一个简易的 WebApplicationInitializer 实现类,这就是 AbstractAnnotationConfigDispatcherServletInitializer
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
// 引入 spring config 配置类
return new Class[]{SpringConfig.class};
}
@Override
protected String[] getServletMappings() {
// 拦截路径
return new String[]{"/"};
}
}
配置类代替 spring-config.xml、mybatis.xml
在 Spring 配置类中使用注解开启 SpringMVC、配置 bean
@Configuration
@ComponentScan(basePackages = {"cade.controller", "cade.service"}) // 扫描 component
@EnableWebMvc // <mvc:annotation-driven />
public class SpringConfig implements WebMvcConfigurer {
// mybatis
@Bean
public SqlSessionFactoryBean sqlSessionFactory() {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(this.dataSource());
// mybatis 配置文件位置
Resource mybatisConfigResource = new ClassPathResource("mybatis-config.xml");
sqlSessionFactoryBean.setConfigLocation(mybatisConfigResource);
// mapper.xml 文件位置
Resource userMapperXML = new ClassPathResource("mapper/UserMapper.xml");
sqlSessionFactoryBean.setMapperLocations(new Resource[]{userMapperXML});
return sqlSessionFactoryBean;
}
// 数据源
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/demo?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("cade");
return dataSource;
}
// Mapper 类扫描,和 @MapperScan 功能相同
@Bean
public MapperScannerConfigurer initMapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
msc.setBasePackage("cade.mapper");
return msc;
}
// <mvc:resources mapping="/static/**" location="classpath:static/" />
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
}