Spring详解

一、spring

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.0.RELEASE</version>
</dependency>

1.1、spring 目的

  • spring 目的是解决企业级应用的复杂性。
  • spring 理念:使现有技术更加容易使用,整合了现有的技术框架。

1.2、spring 是什么

  • spring 是一个开源的、轻量级的、非侵入式的、控制反转和面向切面的容器框架。

1.3、spring 组成

  • spring core
  • AOP
  • ORM
  • DAO
  • Web
  • Context
  • Web MVC

1.4、spring 配置

1.4.1、别名配置

  • 第一种
<?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 id="hello" class="com.sywl.entity.Hello">
      <constructor-arg name="name" value="张三"/>
  </bean>
  <alias name="hello" alias="hello3"/>
</beans>
  • 第二种:可以起多个别名
<?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 id="hello" class="com.sywl.entity.Hello" name="hello2,hello3">
      <constructor-arg name="name" value="张三"/>
  </bean>
</beans>

1.4.2、import 配置

一般用于团队开发使用,可以将多个配置文件,导入合并为一个配置。

// 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="beanUser.xml"/>
    <import resource="beansP.xml"/>
    <import resource="beansC.xml"/>
    <bean id="address" class="com.sywl.entity.Address">
        <property name="name" value="张三"/>
    </bean>
</beans>

1.4.3、scope 配置(bean 作用域)

// spring的bean作用域默认就是单例singleton
<bean id="hello" class="com.sywl.entity.Hello" scope="singleton">
        <constructor-arg name="name" value="张三"/>
    </bean>

二、IOC

2.1、IOC 的本质

IOC 是一种编程思想,由主动的编程变成被动的接收。

  • 控制:由谁控制对象的创建,传统应用程序的对象是由程序本身来控制创建的,使用了 spring 后,由 spring 来创建对象。
  • 反转:程序本身不创建对象,变成现在程序被动的接收对象。
  • 一句话就是:对象由 spring 来创建、管理、装配。

2.2、IOC 创建对象的方式

  1. 通过无参构造创建对象(默认)
  2. 通过有参构造创建对象
    1. 下标赋值,下标从 0 开始。
<bean id="hello" class="com.sywl.entity.Hello" name="hello2">
     <constructor-arg index="0" value="张三"/>
     <constructor-arg index="1" value="21"/>
</bean>
  1. 通过类型创建,不建议使用。
<bean id="hello" class="com.sywl.entity.Hello" name="hello2">
     <constructor-arg type="java.lang.String" value="张三"/>
     <constructor-arg type="java.lang.Integer" value="11"/>
</bean>
  1. 通过参数名来设置。
<bean id="hello" class="com.sywl.entity.Hello" name="hello2">
     <constructor-arg name="name" value="张三"/>
</bean>

三、DI

3.1、依赖注入的几种方式

  1. 构造器注入
  2. set 方式注入
<?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 id="address" class="com.sywl.entity.Address">
     <property name="name" value="张三"/>
 </bean>
 <bean id="student" class="com.sywl.entity.Student">
     <property name="name" value="张三"/>
     <!--注入null-->
     <property name="str">
         <null/>
     </property>
     <!--注入对象-->
     <property name="address" ref="address"/>
     <!--注入数组-->
     <property name="books">
         <array>
             <value>人性的弱点</value>
             <value>海奥华预言</value>
         </array>
     </property>
     <!--注入list集合-->
     <property name="hobbys">
         <list>
             <value>打篮球</value>
             <value>看书</value>
             <value>写字</value>
         </list>
     </property>
     <!--注入map集合-->
     <property name="card">
         <map>
             <entry key="1" value="第一个"/>
             <entry key="2" value="第二个"/>
             <entry key="3" value="第三个"/>
         </map>
     </property>
     <!--注入set集合-->
     <property name="games">
         <set>
             <value>set的第一个</value>
             <value>set的第二个</value>
             <value>set的第三个</value>
         </set>
     </property>
     <!--注入properties-->
     <property name="properties">
         <props>
             <prop key="1">爱打游戏</prop>
             <prop key="2">爱学习</prop>
         </props>
     </property>
 </bean>
</beans>
  1. c 命名空间注入,需要有对应参数的构造器(本质构造器注入)
@Data
public class UserOracle {
 private String name;
 private Integer age;
 public UserOracle(String name, Integer age) {
     this.name = name;
     this.age = age;
 }
}
<!--c命名空间,本质是通过有参构造器来注入属性-->
<bean id="userOracle" class="com.sywl.entity.UserOracle" c:name="c李白" c:age="29"/>
  1. p 命名空间注入,需要有属性的 set 方法(本质 set 注入)
<!--p命名空间,本质是通过set方法注入属性-->
<bean id="userMysql" class="com.sywl.entity.UserMySql" p:name="李白" p:age="28"/>

3.2、bean 的作用域

  1. 单例模式(spring 默认机制)
<bean id="hello" class="com.sywl.entity.Hello" scope="singleton">
     <constructor-arg name="name" value="张三"/>
 </bean>
  1. 原型模式(每个容器中 get 的时候,都会产生一个新的对象)
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
Hello hello = applicationContext.getBean("hello2", Hello.class);// get获取对象时。
<bean id="hello" class="com.sywl.entity.Hello" scope="prototype">
     <constructor-arg name="name" value="张三"/>
 </bean>
  1. 其余的request,session,application,只能在web开发中可以使用到。

3.3、bean 的自动装配(三种装配方式)

  • 自动装配式 spring 满足 bean 依赖的一种方式。
  • spring 会在上下文中自动寻找,并自动给 bean 装配属性。
  1. 在 xml 中显式的配置。
    以上依赖注入的四种方式。
  2. 在 Java 中显式配置。
    @Bean:装配属性
  3. 隐式的自动装配 bean。
    byname: 会自动在容器上下文中查找,和自己对象 set 方法后面的值对应的 beanid。(需要保证所有的 bean 的 id 唯一,并且这个 bean 需要和自动注入的属性 set 方法的值一致)
 <bean id="cat" class="com.sywl.entity.Cat">
     <property name="name" value="小猫"/>
 </bean>
 <bean id="cat" class="com.sywl.entity.Cat" autowire="byName"></bean>

bytype:会自动在容器上下文中查找,和自己需要对象的属性类型相同的bean。(需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致)

 <bean id="cat" class="com.sywl.entity.Cat">
     <property name="name" value="小猫"/>
 </bean>
 <bean id="cat" class="com.sywl.entity.Cat" autowire="byType"></bean>

3.4、隐式的注解装配 bean。

  • @AutoWired:默认通过 byType 的方式实现,而且必须要求这个对象存在!类型不唯一则通过 byName
    如果 AutoWired 不能唯一自动装配上属性,则需要通过@Qualifier(value=”xxx”) 指定名字。
  • @Resource:默认通过 byName 的方式实现,如果找不到名字,则通过 byType 实现,如果两个都找不到就报错。

3.4.1、使用步骤

  1. 导入约束:context 约束
  2. 配置注解支持:context:annotation-config/
<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context
     https://www.springframework.org/schema/context/spring-context.xsd">
 <!--开启注解支持-->
 <context:annotation-config/>
</beans>

3.4.2、注意点

  • @Autowired可以在属性上使用,也可以在 se 方法上使用。
  • 使用@Autowired我们可以不用编写 set 方法,前提是这个自动装配的属性在 IOC 容器中存在,并且符合名字 byName。

四、AOP

4.1、代理模式好处

  1. 可以使被代理对象(真实角色)的操作更加的纯粹,不用关注公共的业务。
  2. 一些公共的其他业务交给代理对象,可以实现业务的分工。
  3. 公共业务发生拓展的时候,方便集中的管理。
  4. 一个动态代理类代理的是一个接口,一般是对应的一类业务。
  5. 一个动态代理类可以代理多个类,只要实现了同一个接口即可。

4.2、静态代理的缺点

  • 一个被代理对象就要产生一个代理对象,代码量会翻倍,开发效率会变低。

4.3、动态代理

  1. “动态代理” 被代理的角色,和” 静态代理” 被代理的角色一样。
  2. 动态代理的类是动态生成的,不是我们直接写好的。
  3. 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    基于接口:JDK 动态代理
    基于类:cglib
    java 字节码实现:javasist
    了解两个:
    Proxy 类:代理,
    InvocationHandler 接口:调用处理程序

4.4、动态代理步骤

  1. 创建真实对象。(需要被代理的对象)
package com.sywl.demo04;
// 基于接口:jdk动态代理
public interface UserService {
 void create();
 void delete();
 void update();
 void query();
}
/**
* 被代理对象
*/
public class UserServiceImpl implements UserService {
 public void create() {
     System.out.println("增加");
 }
 public void delete() {
     System.out.println("删除");
 }
 public void update() {
     System.out.println("更新");
 }
 public void query() {
     System.out.println("查询");
 }
}
  1. 创建处理程序类 ProxyInvocationHandler 实现 InvocationHandler 接口。
package com.sywl.demo04;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 这个类是"调用处理程序类",我们会用这个类,自动生成"代理类"。(基于接口的---JDK动态代理)
*/
public class ProxyInvocationHandler implements InvocationHandler {
 // 被代理的接口,通过set方法注入
 private Object target;
 public void setTarget(Object target) {
     this.target = target;
 }
 // 生成得到"代理类"方法
 public Object getProxy() {
     return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
 }
 // 处理"代理类"调用方法,并返回结果(当"代理类"调用方法时,方法调用将被编码并分派到"调用处理程序"的invoke方法)
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
     // 动态代理的本质,就是使用反射机制实现
     log(method.getName());// 其他业务操作
     Object result = method.invoke(target, args);// 真实角色执行的方法
     log("执行之后");// 其他业务操作
     return result;
 }
 // 添加操作日志(其他业务操作)
 public void log(String msg) {
     System.out.println("log:执行了" + msg + "方法");
 }
}
  1. 客户端调用程序。
package com.sywl.demo04;
public class Client {
 public static void main(String[] args) {
     // 被代理对象(真实角色)
     UserServiceImpl userServiceImpl = new UserServiceImpl();
     // 创建"调用处理程序对象"。代理对象:现在没有
     ProxyInvocationHandler pih = new ProxyInvocationHandler();
     // 通过"调用处理程序"处理"被代理对象(真实角色)",来处理我们要调用的接口对象
     // set方法设置属性参数
     pih.setTarget(userServiceImpl);
     // 获得"代理类"
     UserService proxy = (UserService) pih.getProxy();
     // "代理类"执行方法。此时的方法调用将被编码并分派到"调用处理程序"的invoke方法
     proxy.create();
     System.out.println();
     proxy.delete();
     System.out.println();
     proxy.update();
     System.out.println();
     proxy.query();
 }
}

4.5、AOP 概念

  • 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
  • AOP 是 OOP 的延续,利用 AOP 可以对业务逻辑的各个部分进行隔离,从而降低业务逻辑的耦合性,
  • 提高程序可重用性,同时提高开发的效率。

4.6、AOP 作用

  • 横切关注点:跨越应用程序多个模块的方法或功能。(与我们业务逻辑无关,但需要我们关注的部分就是横切关注点。例如:日志、缓存、安全、事务等等)
  • 切面(Aspect):横切关注点被模块化的特殊对象。它是一个类
  • 通知(Advice):切面必须要完成的工作。它是类中的一个方法
  • 目标(Target):被通知的对象。它是一个接口或方法
  • 代理(Proxy):向目标对象应用通知之后创建的对象。它是代理类
  • 切入点(PointCut):切面通知执行的 “地点” 的定义。(连接点和切入点就是在哪个地方执行,即 invoke 方法执行的地方)
  • 连接点(JointPoint):与切入点匹配的执行点。

4.7、AOP 实现方式一(原生 Spring API 接口)

  1. 导入 spring 包,aop 包。
<!--spring-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.0.RELEASE</version>
</dependency>
<!--aop-->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.4</version>
</dependency>
  1. 被通知的对象,相当于被代理对象。
// 接口
package com.sywl.service;
public interface UserService {
 void create();
 void delete();
 void update();
 void query();
}
// 实现类
package com.sywl.service;
public class UserServiceImpl implements UserService {
 public void create() {
     System.out.println("执行了create方法");
 }
 public void delete() {
     System.out.println("执行了delete方法");
 }
 public void update() {
     System.out.println("执行了update方法");
 }
 public void query() {
     System.out.println("执行了query方法");
 }
}
  1. 创建前置通知类,后置通知类。
// 前置通知类
package com.sywl.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class BeforeLog implements MethodBeforeAdvice {
 /**
  * @param method:要执行的目标对象的方法
  * @param args:参数
  * @param target:目标对象
  * @throws Throwable
  */
 public void before(Method method, Object[] args, Object target) throws Throwable {
     System.out.println(target.getClass().getName() + "的" + method.getName() + "方法被执行了");
 }
}
// 后置通知类
package com.sywl.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
 /**
  * @param returnValue:返回值
  * @param method
  * @param args
  * @param target
  * @throws Throwable
  */
 public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
     System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
 }
}
  1. spring 配置 aop
// 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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <!--注册bean-->
 <bean id="userService" class="com.sywl.service.UserServiceImpl"/>
 <bean id="beforeLog" class="com.sywl.log.BeforeLog"/>
 <bean id="afterLog" class="com.sywl.log.AfterLog"/>
 <!--方式一:使用原生Spring API接口-->
 <!--配置aop:需要导入aop的约束-->
 <aop:config>
     <!--配置切入点:expression表达式,execution(要执行的位置! * * * * *)-->
     <aop:pointcut id="pointcut" expression="execution(* com.sywl.service.UserServiceImpl.*(..))"/>
     <!--执行环绕增强!-->
     <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
     <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
 </aop:config>
</beans>
  1. 执行。
import com.sywl.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest01 {
 public static void main(String[] args) {
     ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
     // 动态代理的是接口:注意点
     UserService userService = context.getBean("userService", UserService.class);
     userService.create();
 }
}

4.8、AOP 实现方式二(自定义类)

  1. 导入 spring 包,aop 包。
  2. 被通知的对象,相当于被代理对象。
  3. 自定义通知类
package com.sywl.diy;
public class DiyPointCut {
 public void before(){
     System.out.println("-------方法执行前--------");
 }
 public void after(){
     System.out.println("-------方法执行后--------");
 }
}
  1. spring 配置 aop
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <!--方式二:自定义类-->
 <bean id="diy" class="com.sywl.diy.DiyPointCut"/>
 <aop:config>
     <!--自定义切面,ref要引用的类-->
     <aop:aspect ref="diy">
         <!--切入点-->
         <aop:pointcut id="point" expression="execution(* com.sywl.service.UserServiceImpl.*(..))"/>
         <!--通知-->
         <aop:before method="before" pointcut-ref="point"/>
         <aop:after method="after" pointcut-ref="point"/>
     </aop:aspect>
 </aop:config>
</beans>
  1. 执行。

4.9、AOP 实现方式三(注解)

  1. 导入 spring 包,aop 包。
  2. 被通知的对象,相当于被代理对象。
  3. 自定义通知类。使用注解标注。
package com.sywl.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* 方式三:使用注解的方式实现AOP
*/
@Aspect // 标注这个类是一个切面
public class AnnotationPointCut {
 @Before("execution(* com.sywl.service.UserServiceImpl.*(..))")
 public void before(){
     System.out.println("-------方法执行前--------");
 }
 @After("execution(* com.sywl.service.UserServiceImpl.*(..))")
 public void after(){
     System.out.println("-------方法执行后--------");
 }
 // 在环绕增加中,我们可以给定一个参数,代表我们要处理切入的点
@Around("execution(* com.sywl.service.UserServiceImpl.*(..))")
 public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("环绕前");
    // 执行方法
    Object proceed = joinPoint.proceed();
    System.out.println("环绕后");
}
}
  1. spring 配置 aop
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <!--方式三:注解方式实现aop-->
 <bean id="annotationPointCut" class="com.sywl.diy.AnnotationPointCut"/>
 <!--开启注解支持:JDK(默认)  cglib-->
 <aop:aspectj-autoproxy proxy-target-class="false"/><!--默认是flase,true时是cglib-->
</beans>
  1. 执行。

五、spring 注解开发

5.1、解决问题:

bean 即@Component,属性注入@Value,衍生的注解@Controller@Service@Repository,自动装配@Autowired@Resource,作用域@Scope

  • @Component@Controller@Service@Repository这四个注解功能都是一样,代表将某个类注册到 spring 中,这个类被 spring 管理了,就是 bean
  • 注解开发的 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"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      https://www.springframework.org/schema/context/spring-context.xsd">
  <!--开启注解支持-->
  <context:annotation-config/>
  <!--扫描注解的包-->
  <context:component-scan base-package="com.sywl.entity"/>
</beans>
  • 实体类 User
package com.sywl.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//@Component等价于<bean id="user" class="com.sywl.entity.User"/>
@Component
@Scope("singleton")
public class User {
  // @Value("张三")等价于<property name="name" value="张三"/>
  @Value("张三")
  private String name;
  public String getName() {
      return name;
  }
  public void setName(String name) {
      this.name = name;
  }
}

5.2、小结

  • xml 更加万能,适用于任何场合;维护简单方便。
  • 注解不是自己类不能使用,维护相对复杂。
  • 建议:xml 用来管理 bean;注解只负责完成属性的注入;使用时需要让注解生效,开启注解支持。
<!--开启注解支持-->
  <context:annotation-config/>
  <!--扫描注解的包-->
  <context:component-scan base-package="com.sywl.entity"/>

5.3、spring 的 Javaconfig

  • Java 来配置文件
package com.sywl.config;
import com.sywl.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
// configuration也会被spring容器管理,注册到容器中,本来就是一个@Componet
// @Configuration代表这个一个配置类,就是我们之前看到的beans.xml
@Configuration
@ComponentScan("com.sywl.entity")
@Import(SywlConfig2.class)
public class SywlConfig {
  // 注册一个bean,就是我们之前在beans.xml中写的bean标签
  // 这个方法的名字,相当于bean标签的id属性
  // 返回值相当于bean标签的class属性
  @Bean
  public User user(){
      return new User();
  }
}
import com.sywl.config.SywlConfig;
import com.sywl.entity.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest01 {
  public static void main(String[] args) {
      // 通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
      ApplicationContext context = new AnnotationConfigApplicationContext(SywlConfig.class);
      User user = context.getBean("user", User.class);
      System.out.println(user.getName());
  }
}

六、spring 整合 mybatis

6.1、整合需要导入的依赖包。

  • junit
  • mybatis
  • mysql
  • spring
  • aop
  • mybatis-spring(spring 和 mybatis 的整合包)
  • 需要注意依赖包的版本问题
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.26</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.2</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.6.RELEASE</version>
</dependency>
<!--spring操作数据库,还需要spring-jdbc-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.6</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.2</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.12</version>
</dependency>

6.2、spring 整合 mybatis 方式一

  1. 配置核心文件。(编写数据源,配置 SqlSessionFactory,配置 SqlSessionTemplate)
// 主配置文件applicationContext.xml;可以把整合mybatis的spring-dao.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <import resource="spring-dao.xml"/>
 <!--第一种方式把sqlSessionTemplate注入到实现类中。第二种方式,可以省略这一步-->
 <bean id="userMapper" class="com.sywl.mapper.UserMapperImpl">
     <property name="sqlSessionTemplate" ref="sqlSession"/>
 </bean>
</beans>
// spring-dao.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <!--DataSource:使用spring的数据源替换Mybatis的配置。 c3p0 dbcp druid
 我们这里使用spring提供的JDBC:org.springframework.jdbc.datasource
 -->
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
     <property name="url" value="jdbc:mysql://localhost:3306/z_mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>
     <property name="username" value="root"/>
     <property name="password" value="xxx"/>
 </bean>
 <!--sqlSessionFactory:注入数据源,可以绑定mybatis配置文件-->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="dataSource" />
     <!--绑定mybatis配置文件:绑定后,mybatis中的配置可以省略-->
     <property name="configLocation" value="classpath:mybatis-config.xml"/>
     <property name="mapperLocations" value="classpath:com/sywl/mapper/*.xml"/>
 </bean>
 <!--SqlSessionTemplate:就是我们使用的sqlSession,注入sqlSessionFactory-->
 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
     <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
     <constructor-arg index="0" ref="sqlSessionFactory"/>
 </bean>
</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="com.sywl.entity"/>
 </typeAliases>
 <!--<settings>
     <setting name="" value=""/>
 </settings>-->
</configuration>
  1. 需要给接口加实现类。
package com.sywl.mapper;
import com.sywl.entity.User01;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
/**
* 方式一:spring接管mybatis时,需要多这个实现类。
*/
public class UserMapperImpl implements UserMapper {
 // 我们所有操作,都使用sqlSession来执行。现在都使用SqlSessionTemplate
 // 在applicationContext.xml文件中注入sqlSessionTemplate
 private SqlSessionTemplate sqlSessionTemplate;
 public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
     this.sqlSessionTemplate = sqlSessionTemplate;
 }
 public List<User01> selectUsers() {
     UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
     return mapper.selectUsers();
 }
}
  1. 将自己写的实现类注入到 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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <import resource="spring-dao.xml"/>
 <!--第一种方式把sqlSessionTemplate注入到实现类中。第二种方式,可以省略这一步-->
 <bean id="userMapper" class="com.sywl.mapper.UserMapperImpl">
     <property name="sqlSessionTemplate" ref="sqlSession"/>
 </bean>
</beans>
  1. 测试使用。
@Test
 public void test(){
     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
     UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
     List<User01> user01s = userMapper.selectUsers();
     for (User01 user01 : user01s) {
         System.out.println(user01);
     }
 }

6.3、spring 整合 mybatis 方式二

  1. 配置核心文件。(编写数据源,配置 SqlSessionFactory,配置 SqlSessionTemplate)
// 主配置文件applicationContext.xml;可以把整合mybatis的spring-dao.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <import resource="spring-dao.xml"/>
 <!--第二种方式加上这一步-->
 <bean id="userMapper2" class="com.sywl.mapper.UserMapperImpl2">
     <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
 </bean>
</beans>
// spring-dao.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <!--DataSource:使用spring的数据源替换Mybatis的配置。 c3p0 dbcp druid
 我们这里使用spring提供的JDBC:org.springframework.jdbc.datasource
 -->
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
     <property name="url" value="jdbc:mysql://localhost:3306/z_mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>
     <property name="username" value="root"/>
     <property name="password" value="xxx"/>
 </bean>
 <!--sqlSessionFactory:注入数据源,可以绑定mybatis配置文件-->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="dataSource" />
     <!--绑定mybatis配置文件:绑定后,mybatis中的配置可以省略-->
     <property name="configLocation" value="classpath:mybatis-config.xml"/>
     <property name="mapperLocations" value="classpath:com/sywl/mapper/*.xml"/>
 </bean>
 <!--SqlSessionTemplate:就是我们使用的sqlSession,注入sqlSessionFactory-->
 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
     <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
     <constructor-arg index="0" ref="sqlSessionFactory"/>
 </bean>
</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="com.sywl.entity"/>
 </typeAliases>
 <!--<settings>
     <setting name="" value=""/>
 </settings>-->
</configuration>
  1. 需要给接口加实现类。
package com.sywl.mapper;
import com.sywl.entity.User01;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
/**
* 第二种方式:可以继承SqlSessionDaoSupport直接获取sqlSession。不需要注入SqlSessionTemplate属性。
* spring接管mybatis时,需要多这个实现类
*/
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
 public List<User01> selectUsers() {
     return getSqlSession().getMapper(UserMapper.class).selectUsers();
 }
}
  1. 将自己写的实现类注入到 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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     https://www.springframework.org/schema/aop/spring-aop.xsd">
 <import resource="spring-dao.xml"/>
 <!--第二种方式加上这一步-->
 <bean id="userMapper2" class="com.sywl.mapper.UserMapperImpl2">
     <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
 </bean>
</beans>
  1. 测试使用。
@Test
public void test(){
 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
 List<User01> user01s = userMapper.selectUsers();
 for (User01 user01 : user01s) {
     System.out.println(user01);
 }
}

七、spring 中的事务

  • 声明式事务: AOP
  • 编程式事务: 需要在代码中,进行事务管理
// spring-dao.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--DataSource:使用spring的数据源替换Mybatis的配置 c3p0 dbcp druid
    我们这里使用spring提供的JDBC:org.springframework.jdbc.datasource
    -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="xxx"/>
    </bean>
    <!--sqlSessionFactory:注入数据源,可以绑定mybatis配置文件-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定mybatis配置文件:绑定后,mybatis中的配置可以省略-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/sywl/mapper/*.xml"/>
    </bean>
    <!--SqlSessionTemplate:就是我们使用的sqlSession,注入sqlSessionFactory-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
    <!--结合AOP实现事物的织入-->
    <!--配置事务通知:通知就是一个方法-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--给事务配置传播特性-->
        <tx:attributes>
            <!--*代表所用方法。以add、delete、update、query开头的方法配置事务。(可以单独配置,也可以配置全部方法)-->
            <tx:method name="*" propagation="REQUIRED"/>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <!--配置切入点:"切入点"就是"通知"执行的地点。目前配置的地点是com.sywl.mapper包下的所有方法-->
        <aop:pointcut id="txPointCut" expression="execution(* com.sywl.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值