Spring二轮学习

1、Spring

1.1 简介

  • Spring:春天——>给软件行业带来春天

  • 2002,首次推出了Spring框架雏形:interface21

  • Rod Johnson作者

  • 使现有技术变得更容易使用,大杂绘

    maven依赖包:

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.1</version>
    </dependency>
    

1.2 优点

  • Spring是一个开源的免费的框架
  • 轻量级,非入侵式的框架
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持事务的处理,支持与其他框架的整合

1.3 组成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v8GPgvXG-1605866070866)(C:\Users\ASUS\Desktop\ssm\Spring5分析图\Spring5模块.bmp)]

2、IOC理论推导

1、dao

2、daoImpl

3、service

4、serviceImpl

  • 在之前的业务中,用户更改需求,需要修改源代码,当代码量大了之后,修改成本代价十分昂贵
  • 使用set方法之后,程序不再具有主动性,而是变成了被动的接收对象
 public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        userService.setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
    }

这种思想,从本质上解决了问题,我们程序员不再去管理对象的创建,大大降低了系统的耦合度,这就是IOC的原型!

IOC本质

控制反转IOC,是一种设计思想,**DI(依赖注入)**是实现IOC的一种方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XiCMbfhl-1605866070869)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119135309545.png)]

控制反转是一种通过描述(XML或者注解)并通过第三方去生产或获取特定对象的方式,在spring中实现控制反转的是IOC容器,其实现方法是依赖注入(DI)

3、HelloSpring

编写一个实体类

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

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 http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="com.cs.pojo.Hello">
        <property name="str" value="HelloSpring"/>
    </bean>
</beans>

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

4、IOC创建对象的方法

1、使用无参构造创建对象,默认!、

2、假设我们要是用有参构造创建对象。

第一种,下标赋值,不建议使用

<bean id="hello" class="com.cs.pojo.Hello">
        <constructor-arg index="0" value="小艾说java"/>
</bean>

第二种,通过类型创建,不建议使用

<!--不建议使用-->
    <bean id="hello" class="com.cs.pojo.Hello">
        <constructor-arg type="java.lang.String" value="小艾说java"/>
    </bean>

第三种,直接通过参数名

<bean id="hello" class="com.cs.pojo.Hello">
        <constructor-arg name="str" value="小艾说java"/>
</bean>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了

5、Spring配置

5.1 别名

<!--别名-->
<alias name="hello" alias="hello2"/>

5.2 Bean的配置

<!--
    id:bean的唯一标识符,对象名
    class:bean对象所对应的全限定名:包名+类名
    name:也是别名,它可以取多个别名
    -->
    <bean id="hello3" class="com.cs.pojo.Hello" name="hello4"></bean>

5.3 import

可以将多个配置文件,导入合并为一个

<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>

6、DI依赖注入

6.1 构造器注入

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rpb802jw-1605866070874)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119143447413.png)]

6.2 Set方法注入【重点】

依赖注入:Set注入

  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象中的所有属性,由容器来注入

【环境搭建】

1、复杂类型

2、真实测试对象

Student类

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private Properties info;
    private String wife;

Address类

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}

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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.cs.pojo.Address">
        <property name="address" value="西安"/>
    </bean>
    <bean id="student" class="com.cs.pojo.Student">
        <!--普通值注入-->
           <property name="name" value="小艾"/>
        <!--Bean注入-->
           <property name="address" ref="address"/>
        <!--数组-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>水浒传</value>
                <value>西游记</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--list-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电影</value>
                <value>玩游戏</value>
            </list>
        </property>
        <!--map-->
        <property name="card">
            <map>
                <entry key="身份证" value="3123213123"/>
                <entry key="银行卡" value="242423432232"/>
            </map>
        </property>
        <!--Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">2e23324324324</prop>
                <prop key="姓名">小艾</prop>
                <prop key="性别"></prop>
            </props>
        </property>
        <!--null值-->
        <property name="wife">
            <null/>
        </property>
    </bean>

</beans>

测试类

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student student = context.getBean("student", Student.class);
        System.out.println(student.toString());
    }

6.3 拓展方式注入

c命名空间和p命名空间

p命名空间,可以直接注入属性值

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/mydb"
        p:username="root"
        p:password="misterkaoli"/>

</beans>

c命名空间

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

6.4 bean的作用域

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lnSPNthB-1605866070877)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119151022859.png)]

1、单例模式(Spring默认机制)

<bean id="student" class="com.cs.pojo.Student" scope="singleton">

2、原型模式:每次从容器中get的时候,都会产生一个新对象

<bean id="student" class="com.cs.pojo.Student" scope="prototype">
public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student student = context.getBean("student", Student.class);
        Student student1 = context.getBean("student", Student.class);
        System.out.println(student==student1);
    }

结果为:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0BiRFLQ3-1605866070880)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119151537056.png)]

3、其余的request、session、application、websocket这些只能在web开发中使用到

7、Bean的自动装配

  • 自动装配是Spring满足bean依赖一种方式
  • Spring会在上下文中自动寻找,并自动给bean装配属性

在Spring中有三种装配的方式

1、在xml中显示的配置

2、在java中显示配置

3、隐式的自动装配bean【重点】

7.1 测试

1、环境搭建

一个人有两个宠物

7.2 ByName自动装配

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.cs.pojo.Cat"/>
    <bean id="dog" class="com.cs.pojo.Dog"/>
    <!--
    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
    -->
    <bean id="people" class="com.cs.pojo.People" autowire="byName">
        <property name="name" value="小艾"/>
    </bean>
</beans>

7.3 ByType自动装配

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.cs.pojo.Cat"/>
    <bean id="dog" class="com.cs.pojo.Dog"/>
    <!--
    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
    -->
    <bean id="people" class="com.cs.pojo.People" autowire="byName">
        <property name="name" value="小艾"/>
    </bean>
</beans>

小结:

  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

7.4 注解实现装配

JDK1.5支持的注解,Spring2.5就支持注解了

要使用注解须知:

  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>

三种注解

@AutoWired

自动装配通过类型,名字

如果AutoWired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)

@Resource:自动装配通过名字,类型

8、使用注解开发

在Spring4之后要使用注解开发,必须要保证AOP的包导入

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YDvPImH0-1605866070883)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119164537604.png)]

使用注解需要导入context约束,增加注解的支持

8.1 bean

//等价于<bean id="user" class="com.cs.pojo.User"/>
@Component
public class User {

8.2 属性如何注入

//等价于<bean id="user" class="com.cs.pojo.User"/>
@Component
public class User {
    //相当于<property name="name" value="小艾"/>
    @Value("小艾")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

8.3 衍生的注解

@Component有几个衍生注解,我们在开发中,会按照mvc三层架构分层

dao【@Repository】

service【@Service】

controller【@Controller】

这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean

8.4 自动装配

@AutoWired

自动装配通过类型,名字

如果AutoWired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)

@Resource:自动装配通过名字,类型

8.5 作用域

@Component
@Scope("prototype")
public class User {
    //相当于<property name="name" value="小艾"/>
    @Value("小艾")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

8.6 小结

xml与注解:

  • xml更加万能,适用于任何场合!维护简单方便
  • 注解 不是自己的类使用不了

9、代理模式

为什么要学习代理模式?因为这就是SpringAOP的底层【SpringAOP和SpringMVC】

9.1 静态代理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0wAyeAf4-1605866070885)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119175335130.png)]

代理模式的分类:

  • 静态代理
  • 动态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理对象的人

代码步骤:

1、接口

//租房
public interface Rent{
    void rent();
}

2、真实角色

//房东
public class Host implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子!");
    }
}

3、代理角色

//代理 中介
public class Proxy implements Rent {
    private Host host;

    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    @Override
    public void rent() {
        host.rent();
        seeHouse();
        hetong();
        fare();
    }

    //看房
    public void seeHouse(){
        System.out.println("中介带你看房子");
    }
    //签合同
    public void hetong(){
        System.out.println("签租赁合同");
    }
    //收中介费
    public void fare(){
        System.out.println("收中介费");
    }
}

4、客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //代理
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共业务就交给代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理

缺点:

一个真实角色就会产生一个代理角色;代码量会翻倍,开发效率会变低

9.2 加深理解

1、接口

public interface UserService {
    void add();
    void delete();
    void update();
    void query();
}

2、真实角色

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("增加了一个用户");
    }

    @Override
    public void delete() {
        System.out.println("删除了一个用户");
    }

    @Override
    public void update() {
        System.out.println("修改了一个用户");
    }

    @Override
    public void query() {
        System.out.println("查询了一个用户");
    }
}

3、代理角色

public class UserServiceProxy implements UserService {
    private UserServiceImpl userService;

    public UserServiceProxy() {
    }

    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }

    @Override
    public void add() {
        log("add");
        userService.add();
    }

    @Override
    public void delete() {
        log("delete");
        userService.delete();
    }

    @Override
    public void update() {
        log("update");
        userService.update();
    }

    @Override
    public void query() {
        log("query");
        userService.query();
    }
    //日志方法
    public void log(String msg){
        System.out.println("使用了"+ msg +"方法");
    }

4、客户端访问代理角色

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        UserServiceProxy proxy = new UserServiceProxy();
        proxy.setUserService(userService);
        proxy.add();
    }
}

AOP

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2xTwQ8T5-1605866070887)(C:\Users\ASUS\AppData\Roaming\Typora\typora-user-images\image-20201119184212266.png)]

9.3 动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
  1. 基于接口:JDK动态代理
  2. 基于类:CGLIB动态代理
  3. java字节码实现:javassist

需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序

万能的动态代理类:

package com.cs.Demo4;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       //动态代理的本质,就是使用反射机制实现
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String msg){
        System.out.println("执行了"+ msg +"方法");
    }
}

客户端访问代理对象

public class Client {
    public static void main(String[] args) {
        //真实角色
        UserServiceImpl userService = new UserServiceImpl();
        //代理角色,不存在
        ProxyInvocationHandler handler = new ProxyInvocationHandler();
        //设置代理对象
        handler.setTarget(userService);
        //动态生成代理类
        UserService proxy = (UserService) handler.getProxy();

        proxy.delete();
    }
}

好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共业务就交给代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可

10、AOP

10.1 什么是AOP

AOP(Aspect-Oriented Programming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善。OOP引入封装、继承和多态性等概念来建立一种对象层次结构,用以模拟公共行为的一个集合。当我们需要为分散的对象引入公共行为的时候,OOP则显得无能为力。也就是说,OOP允许你定义从上到下的关系,但并不适合定义从左到右的关系。例如日志功能。日志代码往往水平地散布在所有对象层次中,而与它所散布到的对象的核心功能毫无关系。对于其他类型的代码,如安全性、异常处理和透明的持续性也是如此。这种散布在各处的无关的代码被称为横切(cross-cutting)代码,在OOP设计中,它导致了大量代码的重复,而不利于各个模块的重用。

10.2 AOP在Spring中的作用

  • 提供声明式事务;允许用户自定义切面

  • 横切关注点:与业务逻辑无关,但是需要关注的部分。如:日志,安全,缓存,事务等

  • 切面:横切关注点被模块化的特殊对象。即,它是一个类

  • 通知:切面必须要完成的工作。即,它是类中的一个方法

  • 目标:被通知对象

  • 代理:向目标对象应用通知之后创建的对象

  • 切入点:切面通知执行的“地点”的定义

  • 连接点:与切入点匹配的执行点

10.3 使用Spring实现AOP

【重点】使用AOP织入,需要导入一个依赖包

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
</dependencies>

方法一:使用Spring的API接口【主要SpringAPI接口实现】

<!--方式一:使用原生Spring API接口-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="pointcut" expression="execution(* com.cs.service.UserServiceImpl.*(..))"/>

        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>

        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

方法二:自定义来实现AOP【主要是切面定义】

<!--方式二:自定义类-->
    <bean id="diy" class="com.cs.diy.DiyPointCut"/>
    <aop:config>
        <!--自定义切面-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.cs.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现

 <!--方式三-->
    <bean id="annotationPointCut" class="com.cs.diy.AnnotationPointCut"/>
    <!--开启注解支持-->
    <aop:aspectj-autoproxy/>
@Aspect   //标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.cs.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("======方法执行前======");
    }
}

测试类

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }

11、整合MyBatis

步骤:

  1. 导入相关jar包

    • junit

    • mybatis

    • mysql数据库

    • spring相关的

    • aop织入

    • mybatis-spring【整合包】

      <dependencies>
              <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>4.12</version>
              </dependency>
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>5.1.47</version>
              </dependency>
              <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis</artifactId>
                  <version>3.5.3</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-webmvc</artifactId>
                  <version>5.1.9.RELEASE</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-jdbc</artifactId>
                  <version>5.1.9.RELEASE</version>
              </dependency>
              <dependency>
                  <groupId>org.aspectj</groupId>
                  <artifactId>aspectjweaver</artifactId>
                  <version>1.8.13</version>
              </dependency>
              <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis-spring</artifactId>
                  <version>2.0.2</version>
              </dependency>
          </dependencies>
      
  2. 编写配置文件

  3. 测试

11.1 回忆MyBatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试
public class MyTest {
    @Test
    public void test() throws IOException {
        String resources  = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);
        SqlSessionFactory sqlSessionFactory = new             SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

11.2 MyBatis-Spring

方式一

  1. 编写数据源配置
  2. sqlSessionFactory
  3. sqlSessionTemplate
  4. 需要给接口加实现类
  5. 将自己写的实现类,注入到Spring中
  6. 测试使用即可
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--DataSource:使用Spring的数据源替换MyBatis的配置-->
    <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?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true"/>
        <property name="username" value="root"/>
        <property name="password" value="1318579525"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/cs/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我们使用的SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能通过构造器注入sqlSessionFactory,因为SqlSessionTemplate没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.cs.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

实现类

public class UserMapperImpl implements UserMapper {
    //在之前,所有的操作都是交给sqlSession来执行,现在,都使用SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

方式二(继承SqlSessionDaoSupport类)

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>

    <bean id="userMapper" class="com.cs.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    <bean id="userMapper1" class="com.cs.mapper.UserMapperImpl1">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

实现类

public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> selectUser() {
       return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

12、声明式事务

12.1 回顾事务

  • 要么都成功,要么都失败
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎
  • 确保数据的一致性

事务的ACID原则:

  1. 原子性:确保要么都成功,要么都失败
  2. 一致性:总数不变
  3. 隔离性:多个业务可能操作同一个资源,要保证互不干扰
  4. 持久性:事务一旦提交,就持久化到数据库里了

12.2 Spring中的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中,进行事务的管理
<!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!--结合AOP实现事务的织入-->
    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <tx:attributes>
            <tx:method name="selectUser" read-only="true"/>
            <tx:method name="addUser" propagation="REQUIRED"/>
            <tx:method name="deleteUser" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.cs.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config> 

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况
  • 如果我们不在Spring中配置声明式事务,我们就需要代码中手动配置事务
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值