Spring5学习·笔记·

1、Spring

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

  • Spring框架以 interface21 框架为基础,于2004年3月24日发布1.0正式版

  • Spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架

  • SSH:Struct2 + Spring + Hibernate!

  • SSM:SpringMvc + Spring + MyBatis

官网:https://spring.io/projects/spring-framework#overview

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

GitHub:https://github.com/spring-projects/spring-framework

maven:这个可以自动导入所有需要的依赖

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

1.2、优点

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

1.3、组成

在这里插入图片描述

1.4、拓展

  • Spring Boot

    • 一个快速开发的脚手架
    • 基于SpringBoot可以快速的开发单个微服务
    • 约定大于配置
  • SpringCold

    • SpringClod 是基于SpringBoot实现的

弊端:配置十分繁琐。

2、IOC理论推导

1.UserDao接口

2.UserDaoImpl实现类

3.UserService 业务接口

4.UserServiceImpl 业务实现类

控制反转:主动权交给用户

private UserDao userDao  // 这个一个接口
    
   
// 利用set进行动态实现值的注入
public void setUserDao(UserDao userDao){
    this.userDao = userDao
}

想调用接口中哪个方法,就在调用上面set时 new 对应方法的实现类(相当于利用 多态 ),就可以做到将控制权交还给用户,降低耦合性,这就是IOC的原型

例:

// 数据库层接口:
public interface A {
    public void a();
}
// 数据库层接口实现类:
1.默认使用的数据库
public class AImpl implements A{
    public void a() {
        System.out.println("这是一个默认的a");
    }
}
======================================
2.用户指定要使用Mysql
    public class AMysqlImpl implements A{

    public void a() {
        System.out.println("这是Mysql的a");
    }
}
=======================================
// 业务层接口:
public interface C {
    public void a();
}
// 业务层接口实现类
public class CImpl implements C{
    private A a;
    public void setA(A a){
        this.a=a;
    }

    public void a() {
        a.a();
    }
}
 // 测试类
public class D {
    public static void main(String[] args) {
        C c = new CImpl();
        ((CImpl)c).setA(new AImpl());
        c.a();
    }
}
// 我们只用着重去更改set方法中new 出来的对象就能选择是用默认还是Mysql,
// 如果不使用set,那么业务实现类中想要实现切换,是不大方便的。

IOC本质

在这里插入图片描述

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

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

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

3、HelloSpring

1、先创建Hello类

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

    public String getStr() {
        return str;
    }

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

    private String str;
}

2、编写Spring的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">

<!--    使用Spring来创建对象,在Spring中这些都称之为Bean
    id:相当于new出来后接受的变量
    class:相当于要new的类
    property:相当于给对象中的属性设置值
    name:类中的变量
    value:可以选择的给变量赋值
    ref:引用Spring容器中创建好的对象
-->
    <bean id="hello" class="com.zou.pojo.Hello">
        <!-- collaborators and configuration for this bean go here -->
        <property name="str" value="z" />
    </bean>


    <!-- more bean definitions go here -->

</beans>

3、编写测试类

public class MyTest01 {
    public static void main(String[] args) {
        // 获取 ApplicationContext 对象,拿到Spring的容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        // 直接getBean来获得类相应的对象
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.getStr());
    }
}

4、IOC创建对象的方式

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

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

    1. 下标赋值,index
        <bean id="user" class="com.zou.pojo.User">
            <!-- collaborators and configuration for this bean go here -->
            <constructor-arg index="0" value=""/>
        </bean>
    
    1. 类型赋值:不建议使用,如果两个参数都是同一类型就完蛋。
    <bean id="user" class="com.zou.pojo.User">
        <!-- collaborators and configuration for this bean go here -->
        <constructor-arg type="java.lang.String" value="邹2"/>
    </bean>
    
    1. 直接通过参数名
     <bean id="user" class="com.zou.pojo.User">
         <constructor-arg name="name" value="邹3"/>
     </bean>
    

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

在Spring中,同一个类只能getBean出一个对象,其他getBean的出来的都是指向同一个对象。

5、Spring配置

5.1、别名

<alias name="user" alias="user2"/> // 我们可以使用别名获取到对象

5.2、Bean的配置

<!-- 
    id :bean 的唯一标识符,也相当于我们学的对象名
    class : bean 对象所对应的全限定名 :包名+类型
    name:也是别名,可以取多个
   -->
    <bean id="user" class="com.zou.pojo.User" name="user3,user4 user5;user6">
        <constructor-arg name="name" value="zoo"/>
    </bean>

5.3、import

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

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

applicationContext.xml

<import resource="beans1.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

使用时直接使用总的配置

6、依赖注入

6.1、构造器注入

上面说过了

6.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;
}

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="address" class="com.zou.pojo.Address"/>
    <bean id="student" class="com.zou.pojo.Student">
<!--        第一种:普通值注入,value-->
        <property name="name" value="邹飞鸣"/>
<!--        第二种:Bean注入,ref-->
        <property name="address" ref="address"/>
<!--        第三种:数组-->
        <property name="books">
            <array>
                <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="12321322"/>
                <entry key="银行卡" value="11111111"/>
            </map>
        </property>
<!--        Set -->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>
<!--        null-->
        <property name="wife">
            <null/>
        </property>
<!--        Properties-->
        <property name="info">
            <props>
                <prop key="driver">12323</prop>
                <prop key="url">213wer</prop>
                <prop key="username">34sfda</prop>
            </props>
        </property>
    </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.getAddress());
    }
}
/*
结果:
    Student{
    name='邹飞鸣'
    address=Address{address='null'}
    books=[红楼梦, 西游记, 水浒传]
    hobbys=[听歌, 敲代码, 看书]
    card={身份证=12321322, 银行卡=11111111}
    games=[LOL, COC]
    wife='null'
    info={url=213wer, driver=12323, username=34sfda}}

  */

6.3、拓展方式注入

我们可以使用p命令空间和c命令空间进行注入:

使用:

<?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"


       xmlns:p="http://www.springframework.org/schema/p"

       xmlns:c="http://www.springframework.org/schema/c"

>


<!--    p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.zou.pojo.User" p:name="邹飞鸣" p:age="20"/>

<!--    c命名空间注入,通过构造器注入:construct-args 注:需要写无参和有参构造方法-->
    <bean id="user2" class="com.zou.pojo.User" c:age="20" c:name="露从今夜白"/>
</beans>

测试:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2", User.class);
        System.out.println(user.toString());
    }
}
结果:
User{name='露从今夜白', age=20}

注意点:p命名和c命名空间需要导入xml约束

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

6.4、bean的作用域

在这里插入图片描述

  1. 单例模式(Spring默认机制)
<bean id="user2" class="com.zou.pojo.User" c:age="11" c:name="cs" scope="singleton"/>
  1. 原型模式:每次从容器中get的时候,都会产生一个新对象。
<bean id="user2" class="com.zou.pojo.User" c:age="11" c:name="cs" scope="prototype"/>
  1. 其余的request 、session、application、这些只能在web开发中使用到

7、Bean的自动装配

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

在Spring中有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示的配置
  3. 隐式 的自动装配bean【重要】

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

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

<!--
        byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id
        即:set方法中的名称会看全部bean标签中的id有没有一致的,如果有就自动配置。
        如果id从 dog - -> ssdog 那么便找不到了即装配失败 
-->
    <bean id="people" class="com.zou.pojo.People" autowire="byName">
        <property name="name" value="小邹"/>
    </bean>
</beans>

7.3、ByType自动装配

这个参数是查找类,如果有指定相同的类,便会自动装配

byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean

注意:如果有多个即:

<bean id="dog" class="com.zou.pojo.Dog"/>
<bean id="dog1" class="com.zou.pojo.Dog"/>

这会直接报错!这是弊端!

总结:

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

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

  • jdk 1.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 我们可以不用编写Set方法,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname

@Nullable 字段标记了这个注解,说明这个字段可以为null;
public @interface Autowired{
    boolean required() default true;
}

测试代码:

public class People{
    
    // 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时,我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!

public class People {
    
    @Autowired
    @Qualifier(value = "cat11")
    private Cat cat;
    private Dog dog;
    private String name;
}

@Resource注解

public class People {

    @Resource
    private Cat cat;
}

小结:

@Resource 和 @Autowired 的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowird 通过byType的方式实现,而且必须要求这个对象存在。【常用】
  • @Resource 默认通过byname的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到的情况下,就报错。【常用】
  • 执行顺序:@Autowird 通过byType的方式实现,@Resource 默认通过byname的方式实现

8、使用注解开发

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

在这里插入图片描述

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

  • @Component : 组件,放在类上,说明这个类被Spring管理了,就是bean。
  1. bean

  2. 属性如何注入

    // 等价于 <bean id="user" class="com.zou.pojo.User"/>
    // @Component 组件
    @Component
    public class User {
        
        public String name;
        
        // 相当于 <property name = "name" value = "邹飞鸣">
        @Value("邹飞鸣")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 衍生注解

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

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

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

  4. 自动装配置

    @Autowired
    @Nullable
    @Resource
    
  5. 作用域(Scope)

    @Component
    @Scope("prototype") // 原型模式
    public class User {
    
        public String name;
    
        // 相当于 <property name = "name" value = "邹飞鸣">
        @Value("邹飞鸣")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  6. 小结

    xml与注解:

    • xml更加万能,适用所有场合,维护简单
    • 注解:不是自己类使用不了,维护相对复杂

    xml 与 注解最佳实践:

    • xml 用来管理bean

    • 注解只负责完成属性的注入

    • 我们使用过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

      <!--    指定要扫描的包,这个包下的注解就会生效-->
          <context:component-scan base-package="com.zou.pojo"/>
          <context:annotation-config/>
      

9、使用Java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做

JavaConfig 是 Spring 的一个子项目,在Spring 4 之后,它成为了一个核心功能!

在这里插入图片描述

实体类:

@Component
@Scope("prototype")
public class User {

    public String name;


    @Value("邹飞鸣") // 注入属性值
    public void setName(String name) {
        this.name = name;
    }
}

配置文件

// 这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component
// @Configuration代表这是一个配置类,就和我们之前看的beans.xml
@Configuration
@ComponentScan("com.zou.pojo")
@Import(ZouConfig2.class)
public class ZouConfig {

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

}

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(ZouConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.name);
    }
}

这种纯java的,在springboot中常见

10、代理模式

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

代理模式的分类:

  • 静态代理
  • 动态代理

10.1、静态代理

不改变原有的业务代码在业务代码外获取到业务代码并适当添加一个需要的功能

角色分析:

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

代理模式的好处:

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

缺点:

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

在这里插入图片描述

10.2、动态代理

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

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

  • InvocationHandler :

    Object invoke(Object proxy,方法 method,Object[] args)throws Throwable
    

    处理代理实例上的方法调用并返回结果。 当在与之关联的代理实例上调用方法时,将在调用处理程序中调用此方法。

    proxy:调用该方法的代理实例

    method:

动态代理好处:

可以写成一个工具类被复用

例:

真实角色:

    // 角色接口:
    public interface User {
    public void add();
    public void delete();
}
   // 接口实现类
public class UserIm implements User{
    public void add() {
        System.out.println("出租了");
    }

    public void delete() {
        System.out.println("不租了");
    }
}

动态代理的代码:

public class ProxyInvocationHandler implements InvocationHandler {

    // 被代理的接口
    private Object target;

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

    // 生成得到代理类
    public Object getProxy(){
         // 返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序。 
         // loader - 类加载器来定义代理类 
         // interfaces - 代理类实现的接口列表 
         // h - 调度方法调用的调用处理函数 
        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);
        return result;
    }
    public void log(String msg){
        System.out.println("执行了"+msg+"方法。");
    }
}

需求角色:

public class Client {
    public static void main(String[] args) {
        // 真实角色
        UserIm user = new UserIm();
        // 代理角色
        ProxyInvocationHandler pih = new ProxyInvocationHandler();

        pih.setTarget(user);// 设置想要代理的对象
        // 动态生成代理类
        User proxy = (User) pih.getProxy();
        proxy.delete();
    }
}

11、AOP

11.1、什么是AOP

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

11.2、AOP在Spring中的作用

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

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

在这里插入图片描述

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

在这里插入图片描述

即AOP在 不改变原有代码的情况下,去增加新功能

11.3、使用Spring实现AOP

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

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

方式一: 使用Spring 的 API接口

用户代码:

// 用户接口:==================================
    public interface User {

    public void add();
    public void delete();

}

// 用户接口实现类 ===============================
public class UserImpl implements User{
    public void add() {
        System.out.println("添加了");
    }

    public void delete() {
        System.out.println("删除了");
    }
}

新添加的需求:

// 执行方法前添加的
public class Log implements MethodBeforeAdvice {

    // method:要执行目标对象的方法
    // args:参数
    // o:目标对象
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("执行了"+method.getName()+",属于"+o.getClass().getName()+" 类");
    }
}
============================================
// 执行方法后添加的
public class AfterLog implements AfterReturningAdvice {

    // returnValue:方法执行后的返回值
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回了:"+returnValue);
    }
}
 

注册bean以及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="user" class="com.zou.pojo.UserImpl"/>
    <bean id="log" class="com.zou.pojo.Log"/>
    <bean id="afterLog" class="com.zou.pojo.AfterLog"/>
<!--方式一:使用原生Spring API接口-->

<!--    配置aop:需要导入aop的约束-->
    <aop:config>
<!--        切入点:expression:表达式,execution(要执行的位置! *(修饰词) *(返回值) *(类名) *(方法名) *(参数))-->
        <aop:pointcut id="pointcut" expression="execution(* com.zou.pojo.UserImpl.*(..))"/><!--(..):代表有多个参数 -->

<!--        执行环绕增加!即:将下面这两个方法,切入进上面的方法中-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

测试:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        // 动态代理的是接口
        User user = context.getBean("user", User.class);
        user.add();
    }
}
结果:
执行了add,属于com.zou.pojo.UserImpl 类
添加了
执行了add方法,返回了:null

11.4、使用自定义类来实现

在上面的基础上,抛弃Log,和AfterLog类,编写自定义类:DiyLog,相当于用自定义类代替前两者。

public class DiyLog {
    public void before(){
        System.out.println("=============在方法前执行================");
    }
    public void after(){
        System.out.println("=============在方法后执行================");
    }
}

在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="user" class="com.zou.pojo.UserImpl"/>
    
<!--    方式二:自定义类-->
    <bean id="diy" class="com.zou.diy.DiyLog"/>

<aop:config>
<!--  自定义切面,ref:要引用的类-->
   <aop:aspect ref="diy">

		<!--切入点与通知整体使用~!-->
		<!--切入点-->
      <aop:pointcut id="point" expression="execution(* com.zou.pojo.UserImpl.*(..))"/>
		<!--通知, aop:before:代表方法前,aop:after:代表方法后-->
      <aop:before method="before" pointcut-ref="point"/>
      <aop:after method="after" pointcut-ref="point"/>

   </aop:aspect>
</aop:config>

测试类不变!用户类不变!

11.5、使用注解实现

有注解的类:

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

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect // 标注这个类是一个切面
public class AnnotationPointCut {

    //@Before的包不要导错了! import org.aspectj.lang.annotation.Before;
    @Before("execution(* com.zou.pojo.UserImpl.*(..))")
    public void before(){
        System.out.println("===========方法执行前=============");
    }

}

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="user" class="com.zou.pojo.UserImpl"/>
   
<!--    方式三: 注册类和开启注解支持!-->
    <bean id="annotationPointCut" class="com.zou.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>
</beans>

用户类不变,测试类不变

结果:

===========方法执行前=============
添加了

12、整合Mybatis

步骤:

1.导入相关jar包

  • junit

  • mybatis

  • mysql数据库

  • spring相关

  • aop织入

  • mybatis-spring【new】

  • <dependencies>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <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.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.0.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.4</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.10</version>
            </dependency>
        </dependencies>
        <!--在build中配置resources,来防止我们资源导出失败的问题-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
    
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    

2.编写配置文件

3.测试

12.1、回忆mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试

12.2、Mybatis-Spring

整合MyBatis方式一

  • 将本来在MyBatis中mybatis-config配置文件中定义的连接数据库的操作移到了spring的配置文件中,并且将sqlSession的获取方式也一并在spring的配置文件中定义好并获得,然后再定义Mapper接口的实现类,作用是传入sqlSession并调用 sqlSession.getMapper(); 方法,即之前Mybatis在测试中写的直接写在了这个实现类中,会有一个返回值,返回得到的结果。

  • 代码:

    spring.xml

    <?xml version="1.0" encoding="UTF8"?>
    <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的配置
            我们这里使用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=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    
    <!--    sqlSessionFactory-->
        <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/zou/mapper/*.xml"/>
         </bean>
    <!--    SqlSessionTemplate:就是我们使用的sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--      只能使用构造器注入sqlSessionFactory,因为它没有set方法  -->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
    
    <!--    注册类:UserMapperImpl-->
        <bean id="userMapper" class="com.zou.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    
    </beans>
    

Mapper接口的实现类:

public class UserMapperImpl implements UserMapper{

    // 我们所有操作,都使用sqlSession来执行,在原来,现在都使用SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

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

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

mybatis-config
<?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.zou.pojo"/>
    </typeAliases>

</configuration>
===============================
Mapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zou.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from mybatis.user;
    </select>
</mapper>

用户类:

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

整合Mybatis方式二:

利用继承一个类去获得SqlSession,。

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

利用注册bean时传入上面继承类需要的sqlSessionFactory这个参数。

<?xml version="1.0" encoding="UTF8"?>
<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="userMapper02" class="com.zou.mapper.UserMapperImpl02">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

测试:

public class MyTest {
    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = context.getBean("userMapper02", UserMapper.class);

        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }

    }
}

13、声明式事务

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况
  • 事务在项目开发中十分重要,设计到数据的一致性和完整性问题。

13.1、利用AOP添加事务支持

即,将本来没有事务支持的方法,通过spring的AOP切面编程去添加事务,可以保证数据操作的,原子性,一致性,隔离性,持久性!

即:成功则都成功,失败则都失败,对于一组事务来讲。

方法:只需要更改配置文件中的东西,不需要更改源代码!

<?xml version="1.0" encoding="UTF8"?>
<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
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    
<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=true&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"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/zou/mapper/*.xml"/>
     </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

<!--    配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" 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" propagation="REQUIRED"/>
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>

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

</beans>

其他代码:

User:
++++++++++++++++++++++++++++++++++++
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}
=================================
UserMapper:
++++++++++++++++++++++++++++++++++++
public interface UserMapper {
    public List<User> selectUser();

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

    // 删除一个用户
    public int deleteUser(int id);
}
===================================
UserMapperImpl:
++++++++++++++++++++++++++++++++++++
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
    public List<User> selectUser() {
        User user = new User(5, "邹1", "123456");

        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(user);
        mapper.deleteUser(5);
        return mapper.selectUser();
    }

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

    }

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

    }
}
==================================
UserMapper.xml:
++++++++++++++++++++++++++++++++++++
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zou.mapper.UserMapper">

    <select id="selectUser" resultType="user">
        select * from mybatis.user;
    </select>

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

    <delete id="deleteUser" parameterType="int">
        deletes from mybatis.user where id=#{id}
    </delete>
</mapper>
===================================
applicationContext.xml:
++++++++++++++++++++++++++++++++++++
<?xml version="1.0" encoding="UTF8"?>
<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.zou.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" 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.zou.pojo"/>
    </typeAliases>

</configuration>

测试代码:

public class MyTest {
    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }

    }
}

结果:
虽然添加用户的代码运行了,但是由于删除的sql语句错误,导致最后没有添加成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值