1、Spring

1.1、简介

  • 2002年,首次推出了Spring雏形:interface21框架;
  • 2004年3月24日发布了1.0版本
  • Rod Johnson ,Spring Framework创始人,著名作者,悉尼大学博士,音乐学专业。
  • Spring理念:使现有的技术更加容易使用,本身就是一个大杂烩,整合了现有的技术框架!
  • SSH:Struct2 + Spring + Hibernate
  • SSM:SpringMvc + Spring + Mybatis

官网:https://spring.io/

github下载地址:https://github.com/spring-projects/spring-framework

官方下载地址:https://repo.spring.io/ui/native/release/org/springframework/spring

mawen依赖:

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

1.2、优点

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

总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!

 

1.3、组成

 

 

1.4、扩展

 

  •  Spring Boot
    • 一个快速开发的脚手架
    • 基于SpringBoot可以快速的开发单个微服务
    • 约定大于配置
  • Spring Cloud
    • Spring Cloud是基于SpringBoot实现的

因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!

 

弊端:发展了太久了之后,违背了原来的理念,配置十分繁琐,人称“配置地狱”!

 

2、IOC理论推导

在我们以前的业务中,用户实际调用的是service层,当用户需求发生改变,比如获取用户方式多了两种,dao层的getUser()方法实现类就多了两种,之前的service层是直接创建一个UserDao类,当需求发生改变时,调用的实现类不同,我们需要在service层改动代码,如果程序代码量十分大,修改一次成本十分昂贵

 

 

如果我们使用一个Set接口实现,就发生了革命性的变化!

 

  •  之前,程序是主动创建对象,控制权是在程序手上,在程序内部代码中创建
  • 使用了set注入后,程序不再具有主动性,而是被动的接收对象

 

 

这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注的在业务的实现上,这是IOC的原型!

IOC本质

控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法。没有IOC的程序中,我们使用面向对象编程,对象的创建于对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建交给第三方,个人认为控制反转就是:获得依赖对象的方式反转了。

 

采用XML方式配置Bean的时候,Bean的定义信息和实现分离的,二采用注解的方式可以将两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

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

 

3、Hello Spring

通过set方法注入:

package com.chen.pojo;

public class User {
    private String str;

    public String getStr() {
        return str;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "str='" + str + '\'' +
                '}';
    }
}
<?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">

    <!--   使用Spring来创建对象,在Spring中这些都称为Bean-->
    <bean id="hello" class="com.chen.pojo.User">
        <property name="str" value="Spring"/>
    </bean>
</beans>
import com.chen.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

创建一个实体类,在xml中配置,取标识符,赋值,就可以在任何地方通过ClassPathXmlApplicationContext()获取ApplicationContext 容器,从容器中取得想要的对象,而不需要自己去创建,对象由Spring来创建,管理,装配!

4、IOC创建对象的方式

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

假设我们要使用有参构造创建对象:

2.下标赋值

<bean id="user" class="com.chen.pojo.User">
        <constructor-arg index="0" value="chen"></constructor-arg>
    </bean>

 3.类型赋值(不推荐

<bean id="user" class="com.chen.pojo.User">
        <constructor-arg type="java.lang.String" value="陈"></constructor-arg>
    </bean>

4.参数名赋值

    <bean id="user" class="com.chen.pojo.User">
        <constructor-arg name="name" value="陈先生"></constructor-arg>
    </bean>

 

 总结:在配置文件加载的时候,容器中管理的对象就已经初始化了,且每配置一个对象就有且只有一个实例,不管被取出多少次。

 

5、Spring配置

5.1、别名

<bean id="user" class="com.chen.pojo.User">
        <constructor-arg name="name" value="陈先生"></constructor-arg>
</bean>
<!--    此时的bean可以通过user或userchen来获取-->
<alias name="user" alias="userchen"></alias>

5.2、Bean的配置

 <!--
     id:唯一标识符
     class:对象对应的全限定名:包名+类名
     name:也是别名,而且比alias更强大,可以取多个别名
     -->
    <bean id="userTwo" class="com.chen.pojo.User" 
          name="user2 user3,user4;u5" >
        <constructor-arg name="name" value="陈先生"/>
    </bean>

5.3、import

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

假设,现在项目由多个人开发,这三个人开发不同的类,不同的类注册在不同的xml中,我们可以利用import将所有人的beans.xml合并为一个总的。

  •  zhang.xml
  • li.xml
  • wang.xml
  • applicationContext.xml

 

 使用的时候直接使用总配置:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

 

 6、依赖注入

6.1、构造器注入

前面说过了

3.2、set方式注入【重点

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

【环境搭建】

1.复杂类型

public class Address {

    private String address;

    public String getAddress() {
        return address;
    }

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

2.真实对象测试

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 String wife;
    private Properties info;

3.beans.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">


    <bean id="student" class="com.chen.pojo.Student">
        <!--   第一种,普通值注入     -->
        <property name="name" value="chen"/>

    </bean>

</beans>

4.测试类

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

 

5.完善注入信息

<?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.chen.pojo.Address">
        <property name="address" value="广东"></property>
    </bean>

    <bean id="student" class="com.chen.pojo.Student">
        <!--   第一种,普通值注入     -->
        <property name="name" value="chen"/>

        <!--   第二种,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>
            </list>
        </property>

        <!--   Map     -->
        <property name="card">
            <map>
                <entry key="身份证" value="44092319991351355"/>
                <entry key="银行卡" value="20153151351351351"/>
                <entry key="公交卡" value="156516513"/>
            </map>
        </property>

        <!--    Set    -->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>王者荣耀</value>
                <value>地下城堡2</value>
            </set>
        </property>

        <!--    null    -->
        <property name="wife">
            <null/>
        </property>

        <!--   Properties     -->
        <property name="info">
            <props>
                <prop key="driver">13153</prop>
                <prop key="url">13s1d535</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

</beans>

 

6.3、扩展方式注入

 可以使用p命名空间和c命名空间进行注入

官方解释:

 

 使用:

<!--   p命名空间注入,可以直接注入属性的值:property(对应set注入)     -->
    <bean id="user" class="com.chen.pojo.User" p:age="18" p:name="chen"/>

    <!--   c命名空间注入,通过构造器注入:constructor(对应构造器注入)     -->
    <bean id="user2" class="com.chen.pojo.User" c:age="18" c:name="北冥的鱼"/>

测试:

 @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user.toString());

        User user2 = context.getBean("user2", User.class);
        System.out.println(user2.toString());
    }
}

 

注意点:p命名空间和c命名空间不能直接使用,需要导入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:p="http://www.springframework.org/schema/p"
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">

 6.4、bean的作用域

官网:

 

 

 

1. Singleton:单例模式【默认模式】

 

 

 

    <bean id="user2" class="com.chen.pojo.User" c:age="18" c:name="北冥的鱼" scope="singleton"/>

对于唯一标识符对象只创建一个,不管容器中取多少次,取到的都是同一个对象

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

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

3.其余的request,session,application,这些只能在web开发中使用

 

7、Bean的自动装配

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

在Spring中有三种装配的方式

1.在xml中显示的配置

2..在java中显示装配

3.隐式的自动装配bean【重要】

 

7.1、测试

1.环境搭建:一个人有两个宠物

7.2、byName自动装配

<bean id="dog" class="com.chen.pojo.Dog"/>
    <bean id="cat" class="com.chen.pojo.Cat"/>

    <!--
      byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id
      -->

    <bean id="people" class="com.chen.pojo.People" autowire="byName">
        <property name="name" value="chen"/>
    </bean>

7.3、byType自动装配

<bean id="dog" class="com.chen.pojo.Dog"/>
    <bean id="cat" class="com.chen.pojo.Cat"/>

    <!--
      byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id
      byType:会自动在容器上下文查找,和自己对象属性类型相同的bean
      -->

    <bean id="people" class="com.chen.pojo.People" autowire="byType">
        <property name="name" value="chen"/>
    </bean>

小结

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

7.4、使用注解实现自动装配

jdk1.5支持注解,spring2.5支持注解

要使用注解须知:

1.导入约束 context:

<!-- 已在后面第二点中加入 -->
xmlns:context="http://www.springframework.org/schema/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

直接在属性上使用即可,也可以在set方法上使用

使用Autowired我们就可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在

测试代码:

public class People {
    private String name;
    @Autowired
    private Dog dog;
    @Autowired
    private Cat cat;

 

使用@Qualifier注解可以在xml对bean的注册时使用与set方法不同的名字,如:

public class People {
    private String name;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
<!--此处开启注解使用支持-->
    <context:annotation-config/>

    <bean id="dog222" class="com.chen.pojo.Dog"/>
   <bean id="dog" class="com.chen.pojo.Dog"/>

在@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解(@Autowired)完成的时候,就可以使用这个注解来指定一个唯一的bean对象注入

 

@Resource

java注解,不是spring注解,同样可以实现自动装配,在byName方式能找到符合的bean时,会自动注入(同一个class可以注册多个bean,只要有一个id符合byName方式),也可以像@Qualifier一样指定一个唯一的bean注入

    @Resource(name = "dog222")
    private Dog dog;

    @Resource
    private Cat cat;

 

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,而且必须要求这个对象存在
  • @Resource默认通过byName的方式实现,如果找不到,则通过byType方式实现,如果两个方式都找不到就报错

 

8、使用注解开发

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

 

 

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

 <context:annotation-config/>

 

8.1、bean

8.2、属性如何注入

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

    //    等价于<property name="name" value="chen"/>
    @Value("北冥的鱼")
    public String name;

}

8.3、衍生的注解

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

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】

这四个注解功能都是一样的,都代表把类装配到Spring容器中

8.4、自动装配

-@Autowired:自动装配,通过byType
    如果@Autowired不能唯一自动装配上属性,则需通过@Qualifier(value="xxx")来实现唯一自动装配
-@Resource:自动装配,默认通过byName,不行则通过byType

 

8.5、作用域

//等价于    <bean id="user" class="com.chen.pojo.User"/>
//@Component 组件
@Component
@Scope("singleton")
public class User {

    //    等价于<property name="name" value="chen"/>
    @Value("北冥的鱼")
    public String name;

}

 

8.6、小结

xml与注解:

  • xml更加万能,使用与任何场合,维护简单方便
  • 注解不是自己类使用不了,维护相对复杂

xml与注解的最佳实践:

  • xml用来管理bean
  • 注解只负责属性注入
  • 我们在使用的过程中,只需要注意一个问题,必须让注解生效,就需要开启注解的支持
  •     <!--  指定要扫描的包,这个包下的注解就会生效  -->
        <context:component-scan base-package="com.chen"/>
        <!--此处开启注解使用支持-->
        <context:annotation-config/>

     

9、使用Java的方式配置Spring

9.1、实体类

@Component
public class User {

    @Value("chen")
    private String name;

    public String getName() {
        return name;
    }

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

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

9.2、配置文件

 

//这个也会被注册到Spring容器中,因为它本来就是一个@Component
//@Configuration代表这是一个配置类,相当于之前的applicationContext.xml
@Configuration
@ComponentScan("com.chen")
@Import(ChenConfig.class)
public class UserConfig {

    //注册一个bean,相当于之前xml中的bean标签
    //这个方法的名字,就相当于xml中bean标签中的id属性
    //这个方法的返回值类型,就相当于xml中bean标签中的class属性
    @Bean
    public User getUser() {
        return new User();//就是返回要注入到bean的对象
    }

}

9.3、测试类

 public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
        User getUser = context.getBean("getUser",User.class);
        System.out.println(getUser.toString());

    }

这种纯Java的配置方式,在SpringBoot中随处可见

 

10、代理模式

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

代理模式的分类:

  • 静态代理
  • 动态代理

 

 

 

10.1、静态代理

角色分析:

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

代码步骤:

1.接口

 

 

 2.真实角色

 

 

 3.代理角色

 

 

 4.客户端访问代理模式

 

 

 

代理模式的好处:

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

缺点:

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

10.2、加深理解

 

 

 10.3、动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口:JDK动态代理【我们在这里使用】
    • 基于类:cglib
    • java字节码实现:javasist

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

 

动态代理的好处:

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

 

11、AOP

11.1、什么是AOP

AOP(Aspect Oriented Programming),意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生泛型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使业务各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

 

 

 11.2、AOP在Spring中的作用

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

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

 

 

 

 11.3、使用Spring实现AOP

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

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

 

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

<!--    配置aop,需要导入aop约束  -->
    <!--  方式一:使用原生Spring API 接口 -->
    <aop:config>
        <!--   切入点:expression:表达式:excution(要执行的位置 )     -->
        <aop:pointcut id="pointcut" expression="execution(* com.chen.service.UserServiceImpl.*(..))"/>

        <!--   执行环绕增加     -->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

 

方式二:使用自定义类来实现接口:【主要是切面定义】

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

    </aop:config>

方式三:使用注解实现

//方式三:使用注解方式实现AOP

@Aspect//标注这是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.chen.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("============方法执行前(AnnotationPointCut)===============");
    }

    @After("execution(* com.chen.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("============方法执行后(AnnotationPointCut)===============");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理的切入的点
    @Around("execution(* com.chen.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前(AnnotationPointCut)===============");
        //执行方法
        Object proceed = joinPoint.proceed();
        System.out.println("环绕后(AnnotationPointCut)===============");
    }
}

 

12、整合Mybatis

步骤:

1、导入相关jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入
  • mybatis-spring【new】

2、编写配置文件

3、测试

 

12.1、回忆Mybatis

1、编写实体类

2、编写核心配置文件

3、编写接口

4、编写Mapper.xml

5、测试

 

12.2、Mybatis-Spring

文档:http://mybatis.org/spring/zh/index.html

 

1、编写数据源配置

2、sqlSessionFactory

3、sqlSessionTemplate

4、需要给接口加实现类【】

5、将自己写的实现类,注入到Spring中

6、测试

代码:

User

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

UserMapper

import java.util.List;

public interface UserMapper {
    public List<User> selectUser();
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.chen.dao.UserMapper">

    <select id="selectUser" resultType="com.chen.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

UserMapperImpl

import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;

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();
    }
}

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.chen.pojo"/>
    </typeAliases>
<!--    <mappers>-->
<!--        <mapper resource="com/chen/dao/UserMapper.xml"/>-->
<!--    </mappers>-->
</configuration>

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

    <!--    DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid-->
    <!--    我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource-->

    <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="123456"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/chen/dao/*.xml"/>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--        只能使用构造器注入sqlSessionFactory 因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

</beans>

 

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="spring-dao.xml"/>

    <bean id="userMapper" class="com.chen.dao.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

 

13、声明式事务

1、回顾事务

  • 把一组业务当成一个业务来做,要么都成功,要么都失败
  • 事务在项目开发中,十分的重要,设计到数据的一致性问题,不能马虎
  • 确保完整性和一致性

事务ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写在存储器中

 2、Spring中的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中,进行事务的管理

思考:

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况
  • 如果不在Spring中配置声明式事务,我们就需要在代码中手动配置事务!
  • 事务在项目的开发中十分重要,设计到数据的一致性和完整性问题,不容马虎!

User:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

UserMapper接口

import java.util.List;

public interface UserMapper {
    public List<User> selectUser();

    //添加一个用户
    public int addUser(User user);

    //删除一个用户
    public int deleteUser(int id);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.chen.Mapper.UserMapper">

    <select id="selectUser" resultType="com.chen.pojo.User">
        select * from mybatis.user
    </select>

    <insert id="addUser" parameterType="user">
        insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>
</mapper>

UserMapperImpl

import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{

    @Override
    public List<User> selectUser() {

        User user = new User(8, "小王", "123456");

        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);

        mapper.addUser(user);
        mapper.deleteUser(7);
        return mapper.selectUser();
    }

    @Override
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

mybaits-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.chen.pojo"/>
    </typeAliases>
</configuration>

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:tx="http://www.springframework.org/schema/tx"
       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/tx
        https://www.springframework.org/schema/tx/spring-tx.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.DriverManagerDataSource-->

    <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="123456"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/chen/Mapper/*.xml"/>
    </bean>

    <!--    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
    <!--        &lt;!&ndash;        只能使用构造器注入sqlSessionFactory 因为它没有set方法&ndash;&gt;-->
    <!--        <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">
        <!--给那些方法配置事务-->
        <!--  配置事务的传播特性:new propagation  -->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--  配置事务的切入  -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.chen.Mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

 

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="spring-dao.xml"/>

    <bean id="userMapper" class="com.chen.Mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

测试:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}

 

原文地址:http://www.cnblogs.com/chen-z-w/p/16808321.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性