SpringMvc+Spring+MyBatis 基于注解整合
最近在给学生们讲Spring+Mybatis整合,根据有的学生反映还是基于注解实现整合便于理解,毕竟在先前的工作中团队里还没有人完全舍弃配置文件进行项目开发,由于这两个原因,我索性参考spring官方文档研究出完全基于注解整合ssm框架。毕竟无配置化也是Spring官方所推行的,要不SpringBoot存在的意义为何嘛
一。整合思路
1)目标:毫无保留的将配置文件的所有配置项改变注解加创建对象的方式实现
2)Spring提供的 @Bean @Configuration @ComponentScan @EnableTransactionManagement @EnableWebMvc 等 需要知道其含义
二。创建spring-mvc的web项目
1) 项目结构目录:
在这里web.xml里不写任何配置
三。在config包下分别创建配置类与属性文件
1. AppConfig.java
package com.bdqn.lyrk.ssm.study.app; import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource;
import java.io.IOException; /**
* spring的配置类
*
* @author chen.nie
* @date 2018/6/24
**/
@Configuration //表明此类是配置类
@ComponentScan // 扫描自定义的组件(repository service component controller)
@PropertySource("classpath:application.properties") // 读取application.properties
@MapperScan("com.bdqn.lyrk.ssm.study.app.mapper") //扫描Mybatis的Mapper接口
@EnableTransactionManagement //开启事务管理
public class AppConfig { /**
* 配置数据源
*
* @date 2018/6/24
**/
@Bean
public DataSource dataSource(PropertiesConfig propertiesConfig) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername(propertiesConfig.getUserName());
dataSource.setPassword(propertiesConfig.getPassword());
dataSource.setUrl(propertiesConfig.getUrl());
dataSource.setDriverClassName(propertiesConfig.getDriverClass());
return dataSource;
} /**
* 配置mybatis的SqlSessionFactoryBean
*
* @param dataSource
* @param propertiesConfig
* @return
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, PropertiesConfig propertiesConfig) throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage(propertiesConfig.getMybatisTypeAliasPackages());
// 动态获取SqlMapper
PathMatchingResourcePatternResolver classPathResource = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(classPathResource.getResources(propertiesConfig.getMapperLocations())); return sqlSessionFactoryBean;
} /**
* 配置spring的声明式事务
*
* @return
*/ @Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
return dataSourceTransactionManager; } @Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
return propertySourcesPlaceholderConfigurer;
} }
没什么好说的,这里主要创建Spring与Mybatis整合的相关对象以及声明式事务切面,我们把配置文件中的东西通通用java代码创建,注意@Bean注解的使用
2.DispatcherConfig
package com.bdqn.lyrk.ssm.study.config; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; import java.util.Properties; @Configuration
@EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter { @Autowired
private PropertyConfig propertyConfig; @Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix(propertyConfig.getWebViewPrefix());
internalResourceViewResolver.setSuffix(propertyConfig.getWebViewSuffix());
return internalResourceViewResolver;
} /**
* 设置统一错误处理要跳转的视图
*
* @return
*/
@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.getProperty("java.lang.Exception", "error");
simpleMappingExceptionResolver.setExceptionMappings(properties);
return simpleMappingExceptionResolver;
} /**
* 添加静态资源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(propertyConfig.getWebStaticHandler()).addResourceLocations(propertyConfig.getWebStaticResource()).setCachePeriod(propertyConfig.getWebStaticCachedPeriod());
} /**
* 添加拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
}
}
此处配置SpringMVC的视图解析器,静态资源等,依旧照搬配置文件中的代码
3.PropertiesConfig
package com.bdqn.lyrk.ssm.study.config; 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.context.support.PropertySourcesPlaceholderConfigurer; @Configuration
@PropertySource("classpath:application.properties")
public class PropertyConfig { @Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.driver}")
private String driver;
@Value("${spring.datasource.user}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.web.view.prefix}")
private String webViewPrefix;
@Value("${spring.web.view.suffix}")
private String webViewSuffix;
@Value("${spring.web.static.handler}")
private String webStaticHandler;
@Value("${spring.web.static.resource}")
private String webStaticResource;
@Value("${spring.web.static.cache.period}")
private Integer webStaticCachedPeriod;
@Value("${mybatis.type.alias.package}")
private String mybatisTypeAliasPackage; public String getWebViewPrefix() {
return webViewPrefix;
} public String getWebViewSuffix() {
return webViewSuffix;
} public String getWebStaticHandler() {
return webStaticHandler;
} public String getWebStaticResource() {
return webStaticResource;
} public Integer getWebStaticCachedPeriod() {
return webStaticCachedPeriod;
} public String getMybatisTypeAliasPackage() {
return mybatisTypeAliasPackage;
} public String getUrl() {
return url;
} public String getDriver() {
return driver;
} public String getUser() {
return user;
} public String getPassword() {
return password;
} @Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
此处用于读取application.properties的文件内容 注意@Value与@PropertySource的含义
4.MyWebAppInitializer
package com.bdqn.lyrk.ssm.study.config; import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException; /**
* 初始化servlet WebApplicationContext 相关
*
* @author chen.nie
* @date 2017/12/28
**/
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{AppConfig.class};
} @Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{DispatcherServlet.class};
} @Override
protected String[] getServletMappings() {
return new String[]{"/"};
} /**
* 添加过滤器
*
* @return
*/
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[]{characterEncodingFilter};
}
}
在这里请大家关注一下这个类,这段代码的含义和配置SpringMVC的含义一样:
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
5. application.properties
#数据库连接
spring.datasource.user=root
spring.datasource.password=root
spring.datasource.driver=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/MySchool?characterEncoding=utf-8&useSSL=false
#web设置相关
spring.web.view.prefix=/WEB-INF/jsp/
spring.web.view.suffix=.jsp
spring.web.static.handler=/assets/**
spring.web.static.resource=classpath:/assets/
spring.web.static.cache.period=360000
#mybatis设置相关
mybatis.type.alias.package=com.bdqn.lyrk.ssm.study.entity
6.创建MyBatis对应的mapper
package com.bdqn.lyrk.ssm.study.mapper; import com.bdqn.lyrk.ssm.study.entity.StudentEntity;
import org.apache.ibatis.annotations.Select; import java.util.List; public interface StudentMapper { @Select("select * from Student")
List<StudentEntity> selectAll();
}
7.创建业务逻辑
package com.bdqn.lyrk.ssm.study.service.impl; import com.bdqn.lyrk.ssm.study.entity.StudentEntity;
import com.bdqn.lyrk.ssm.study.mapper.StudentMapper;
import com.bdqn.lyrk.ssm.study.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service
public class StudentServiceImpl implements IStudentService {
@Autowired
private StudentMapper studentMapper; @Override
public List<StudentEntity> selectAll() {
return studentMapper.selectAll();
} @Transactional
@Override
public int save(StudentEntity studentEntity) {
return 0;
} }
8.创建Controller
package com.bdqn.lyrk.ssm.study.controller; import com.bdqn.lyrk.ssm.study.entity.StudentEntity;
import com.bdqn.lyrk.ssm.study.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller
public class IndexController {
@Autowired
private IStudentService studentService; @GetMapping("/index")
public String index(ModelMap modelMap) {
List<StudentEntity> list = studentService.selectAll();
modelMap.put("students", list);
return "index";
}
}
9.index.jsp文件中内容
<%--
Created by IntelliJ IDEA.
User: chen.nie
Date: 2017/12/23
Time: 下午8:40
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<c:forEach items="${students}" var="student">
${student.stuName}
</c:forEach>
</body>
</html>
10.启动tomcat后访问http://localhost:8080/portal/index得到如下界面
OK!大功告成,注意前4步里面注解的运用,后面的步骤和往常的写法无异,想必大家都很熟悉了吧。
SpringMvc+Spring+MyBatis 基于注解整合的更多相关文章
- Spring+Mybatis基于注解整合Redis
基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载 ...
- springMVC,spring,mybatis全注解搭建框架--第一步,让框架跑起来
自己从事java开发工作也有一年多了,自己却没有亲手搭建一个完整的框架.于是今天自己动手搭建一个,过程中遇到一些问题,倒腾了大半天终于搞定了. 现在给大家分享一下过程,自己也记录下来,以后学习参考使用 ...
- SpringMVC+Spring+Mybatis+Maven+mysql整合
一.准备工作1.工具:jdk1.7.0_80(64)+tomcat7.0.68+myeclipse10.6+mysql-5.5.48-win322. 开发环境安装配置.Maven项目创建(参考:htt ...
- SSM(SpringMVC+Spring+MyBatis)三大框架使用Maven快速搭建整合(实现数据库数据到页面进行展示)
本文介绍使用SpringMVC+Spring+MyBatis三大框架使用Maven快速搭建一个demo,实现数据从数据库中查询返回到页面进行展示的过程. 技术选型:SpringMVC+Spring+M ...
- spring + Mybatis + pageHelper + druid 整合源码分享
springMvc + spring + Mybatis + pageHelper + druid 整合 spring 和druid整合,spring 整合druid spring 和Mybatis ...
- 3.springMVC+spring+Mybatis整合Demo(单表的增删该查,这里主要是贴代码,不多解释了)
前面给大家讲了整合的思路和整合的过程,在这里就不在提了,直接把springMVC+spring+Mybatis整合的实例代码(单表的增删改查)贴给大家: 首先是目录结构: 仔细看看这个目录结构:我不详 ...
- 2.springMVC+spring+Mybatis整合
前面已经说了,springMVC+spring+Mybatis的整合思路了,现在就照着这个思路来做一下: 在开始之前先来看一下工程的目录结构: config这个目录底下放的都是配置文件: mybati ...
- SpringMVC+Spring+Mybatis整合
SpringMVC+Spring+Mybatis整合 导包 配置jdbc.properties.log4j.properties jdbc.driver=com.mysql.jdbc.Driver j ...
- springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解
@_@ 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) myba ...
随机推荐
- 【iOS】OC-AFNetworking 2.0 跟踪文件上传进度
我是较新的 AFNetworking 2.0.使用下面的代码片段,我已经能够成功地将一张照片上传到我的 url.我想要跟踪的增量上载进度,但我找不到这样做 2.0 版的示例.我的应用程序是 iOS 7 ...
- 201621123027 Week02-Java基本语法与类库
Week02-Java基本语法与类库 1.本周学习总结 关键词:基本语法,数据类型,包装类 本周讲了Java的基本数据类型和包装类: 数据类型主要分为八类(byte,short,int,long,do ...
- Hibernate之深入Hibernate的配置文件
1.创建Configuration类的对象 Configuration类的对象代表了应用程序到SQL数据库的映射配置.Configuration类的实例对象,提供一个buildSessionFacto ...
- 使用Github pages+jekyll搭建自己的博客(windows版)
最近突发奇想,想试试GitHub pages来搭建博客.网上一搜一大堆,嗯...看来还是挺简单的...于是自己撸起袖子干...... 结果对于我这种GitHub注册过,git 没用过,ruby.jek ...
- php代码一样,编码不同报错
php代码一样,编码不同报错 两个php代码完全一样,但是就报错,比如说声明比如在very first,这种,可以把编码设置utf-8 无bom
- Docker学习笔记 - Docker的镜像
一个容器实际上是运行在宿主机上的一个进程. 只不过在启动这个进程之前进行了一些特殊处理,让这个容器进入了一个全新的虚拟环境,与宿主机的环境分开, 所以这个进程及其子进程认为自己运行在一个独立的世界里面 ...
- Homebrew update error not work on OSX
brew update 错误是这样的 chown: /usr/local: Operation not permitted 然后网上osx 10.11, 10.12的解决方法这样的 The probl ...
- centOs6.5配置jdk及其注意事项
1.下载jdk1.7 百度云链接: https://pan.baidu.com/s/15vXLO2eV18eVvmt-R5jGnQ 密码: 1gd6 2.解压压缩包 通过终端在/usr/local下新 ...
- Java8新特性第2章(接口默认方法)
在Java中一个接口一旦发布就已经被定型,除非我们能够一次性的更新所有该接口的实现,否者在接口的添加新方法将会破坏现有接口的实现.默认方法就是为了解决这一问题的,这样接口在发布之后依然能够继续演化. ...
- Qt编译oci教程
Qt编译OCI教程 上图oci.dll 不是oci.lib 我很奇怪网上大部分教程都是写的oci.lib,其实大家可以去oracle目录找一下这个文件,看看是不是在这个目录,我找了一下没发现.而lib ...