06-Spring框架整合

nobility 发布于 2022-04-01 2863 次阅读


Spring框架整合

整合MyBatis

需要使用到mybatis-spring整合包,已以及Spring和MyBatis(包括数据库驱动),将下面的依赖代码加入pom.xml文件中,也可从MyBatis官方Github中查找到Spring项目进行下载

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>x.x.x</version>
</dependency>

mybatis-config.xml

配置全局MyBatis配置文件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>
  
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>	<!--开启蛇形命名法到驼峰命名法映射一-->
  </settings>
  
  <typeAliases>
      <package name="com.entity"/>  <!--别名定义,该包下的所有实体类可使用首字母小写的类名表示-->
  </typeAliases>
  
</configuration>

dataSource.properties

配置全局数据库连接池配置文件druidDataSource.properties,具体如下:

# 最好增加jdbc前缀,否则可能会与当前系统中的变量冲突
# 连接参数
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=root

# 连接池参数
jdbc.initialSize=5
# 初始化连接数量
jdbc.maxActive=10
# 最大连接数量
jdbc.minIdle=2
# 最小连接数量
jdbc.maxWait=3000
# 连接申请超时时间

applicationContext.xml

配置全局Spring配置文件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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="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">
  <context:component-scan base-package="com"/>  <!--开启IOC注解扫描-->
  <aop:aspectj-autoproxy/>  <!--开启AspectJ自动代理-->
  
  <!--配置数据源,使用Druid数据库连接池-->
  <context:property-placeholder location="classpath:druidDataSource.properties"/>  <!--从外面读取数据库连接池配置,下面使用 ${} 方式引用-->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" 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}"/>

    <property name="initialSize" value="${jdbc.initialSize}"/>
    <property name="maxActive" value="${jdbc.maxActive}"/>
    <property name="minIdle" value="${jdbc.minIdle}"/>
    <property name="maxWait" value="${jdbc.maxWait}"/>
  </bean>
  
  <!--使用mybatis-spring包中提供的SqlSession工厂,注入数据源和配置文件整合MyBatis-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
  </bean>
  <!--使用mybatis-spring包中提供的Mapper扫描,将所有Mapper接口以接口名首字母小写形式加入到IOC容器中-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>  <!--注入SqlSession工厂-->
    <property name="basePackage" value="com.dao"/>  <!--注入Mapper接口所存在的包-->
  </bean>
  
  <!--创建jdbc事务管理器,注入连接池-->
  <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  </bean>
  <!--根据jdbc事务管理器,创建事务通知-->
  <tx:advice id="dataSourceTransactionManagerAdvice" transaction-manager="dataSourceTransactionManager">
    <tx:attributes>
      <!--以get、find、search开头的方法,设置为只读事务-->
      <tx:method name="get*" read-only="true"/>
      <tx:method name="find*" read-only="true"/>
      <tx:method name="search*" read-only="true"/>
      <!--其他方法,事务传播类型使用REQUIRED,即所有方法都应该在一个事务中执行-->
      <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
  </tx:advice>
  <!--
  使用aop对事务方法进行代理
  对service包下的所有类所有方法都进行事务处理,因为dao中是基础SQL语句
  而service中是组合的dao中的方法,所以要将该包开启声明事务
  -->
  <aop:config>
    <aop:advisor advice-ref="dataSourceTransactionManagerAdvice" pointcut="execution(* *..service..*.*(..))"/>
    <!--该切点表达式表示名为service包及其子包中的所有方法-->
  </aop:config>
</beans>

文件上传

整合Commons-fileUpload,需要使用到SpringMVC,并将下面的依赖代码加入pom.xml文件中

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>x.x.x</version>
</dependency>

将以下配置加入到全局Spring配置文件applicationContext.xml

<!-- 文件上传的配置,multipartResolver不能写错 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="1024000"/>  <!--单次上传文件的总大小不能超过1MB,多文件上传也算一次上传-->
  <property name="defaultEncoding" value="utf-8"/>  <!--请求编码格式,必须与jsp的pageEncoding一致-->
  <property name="maxInMemorySize" value="4096"/>  <!--读入内存4KB向磁盘刷新一次-->
</bean>

控制器代码

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {  //若是多文件上传使用List集合接收参数即可
  String uploadDir = "upload";  //上传文件目录
  if (!file.isEmpty()) {  //若有上传
    String filename = file.getOriginalFilename();  //获取原来的文件名
    String path =  request.getServletContext().getRealPath(uploadDir);  //获取上传目录的的绝对路径

    int idx = filename.lastIndexOf(".");
    String exName = filename.substring(idx);  //截取文件后缀名
    filename = UUID.randomUUID().toString().replace("-", "") + exName;  //生成随机UUID拼接后缀名,修改文件名避免上传重名文件被覆盖
    
    try {
      file.transferTo(new File(path + File.separator + filename));  //文件转存
      String fileRPath = request.getServletContext().getContextPath() + "/" + uploadDir + "/" + filename; //拼接文件符合src的相对路径
      return "上传成功,URL地址为:" + fileRPath;
    } catch (IOException e) {
      e.printStackTrace();
      return "上传失败";
    }
  }
  return "未上传";
}

使用下面JSP页面进行测试

<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
  <!-- 必须指定enctype为multipart/form-data -->
    <input type="text" name="name">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
此作者没有提供个人介绍
最后更新于 2022-04-01