spring学习笔记

最近跟着b站狂神说老师学习spring5,自整理学习笔记(p1-p22 之后学到再补上),点此跳转视频
需要源码或者md格式的笔记留言邮箱我发送


1、Spring

1.1 导入maven包

        <!--导入spring的maven依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--倒入spring jdbc依赖-->
        <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 组成

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

1.4 拓展

现代化的java开发 基于Spring的开发

在这里插入图片描述

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

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

弊端:发展太久之后违背了原来的理念,配置十分繁琐

2、IOC理论

1、UserDao接口

2、UserDaoImpl实现类

3、UserService接口

4、UserServiceImpl实现类

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序
代码量十分大,修改一次的成本代价十分昂贵!

在这里插入图片描述

使用set注入,代码发生革命性的区别

    //引入Dao对象
    private UserDao userDao;

    //利用set进行动态创建(set注入,setUserDao后面是一个接口,)
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
  • 之前,程序是主动创建对象,控制权在程序员手上
  • 使用set注入时候,程序不在拥有主动性,而是被动创建对象

这种思想从本质上解决了问题,程序员不在管理对象创建,系统耦合性大大降低,能够更加专注的在业务逻辑上。

这是IOC的原型。
在这里插入图片描述

3、IOC本质

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

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一-体,
Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转
的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

4、IOC创建对象的方式

1、当赋值使用property时候,使用的是无参构造创建对象

    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="str" value="Spring"></property>
    </bean>

2、使用有参构造

   <!--第一种根据参数的下标赋值  从0开始-->
   <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg index="0" value="uzi"></constructor-arg>
   </bean>

    <!--第二种使用type  不建议使用-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg type="java.lang.String" value="lisi"></constructor-arg>
    </bean>

    <!--第三种 通过参数名,常用-->
    <bean id="user" class="com.kuang.pojo.User">
        <constructor-arg name="name" value="wangwu"></constructor-arg>
    </bean>

3、总结:当获得这个spring容器时候,当容器中所有的对象都被初始化了,且都只有一个,默认创建单例,可以再配置中通过scope修改

5、Spring配置

5.1 别名

    <!--如果添加了别名,也能通过别名来获取对象-->
    <alias name="user" alias="userNew"></alias>
User user = (User) context.getBean("user");
//上一步等价于
User user = (User) context.getBean("userNew");

5.2 Bean配置

    <!--第三种 通过参数名,常用-->
    <!--
    id:bean的唯一标识符,也就是相当于我们说的对象名
    class:bean对象所对应的的全限定名,要写全,包名+类名
    name:也是别名,而且name可以取多个别名
    -->
    <bean id="user" class="com.kuang.pojo.User" name="user01 u02" >
        <constructor-arg name="name" value="wangwu"></constructor-arg>
    </bean>

5.3 import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利
用import将所有人的beans.xml合并为一个总的!

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

applicationContext.xml

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

6、依赖注入(DI)

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;
    private Properties info;
    
    //get set方法的等。。。
 }

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.kuang.pojp.Student">
        <!--第一种普通值注入 使用value-->
        <property name="name" value="zhangsan"/>
    </bean>
</beans>

4、测试类

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

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.kuang.pojp.Address">
        <property name="address" value="湖南"/>
    </bean>

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

        <!--第二种bean注入,引用注入-->
        <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="343141123122421"/>
                <entry key="学生证" value="10822398"/>
            </map>
        </property>

        <!--第六种set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>COD</value>
            </set>
        </property>

        <!--第七种 空值注入-->
        <property name="wife">
            <null/>
        </property>

        <!--第八种,配置文件-->
        <property name="info">
            <props>
                <prop key="学号" >20190525</prop>
                <prop key="性别" >男性</prop>
                <prop key="名字" >张三</prop>
                <prop key="username" >root</prop>
                <prop key="password" >1001</prop>
            </props>
        </property>
    </bean>
</beans>

6.3 拓展方式注入

我们可以使用p命名空间(property)和c命名空间(construction)进行注入,p命名空间和c命名空间不能直接使用,要导入xml约束

       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/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"
       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">

    <!--p命名空间注入  可以直接注入属性的值-->
    <bean id="user" class="com.kuang.pojo.User" p:name="lisi" p:age="18"/>

    <!--c命名空间注入 通过构造器注入-->
    <bean id="user2" class="com.kuang.pojo.User" c:age="20" c:name="kuang"/>

</beans>

测试类

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

6.4、Bean的作用域

在这里插入图片描述

  1. singleton 单例模式(Spring默认使用单例模式)全局都只有一个对象

    <bean id="user2" class="com.kuang.pojo.User" c:age="20" c:name="kuang" scope="singleton"/>
    
  2. prototype 原型模式 ,每一次从容器中get的时候,都会产生一个新对象

     <bean id="user2" class="com.kuang.pojo.User" c:age="20" c:name="kuang" scope="prototype"/>
    

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

7、Bean的自动装配

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

在spring中有三种装配的方式

1.在xml中显示装配

2.在Java代码中显示装配

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

7.1 测试

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

7.2 byName自动装配

    <!--
    autowire="byName"  会自动在容器上下文中查找 和自己对象set方法后面的值对应的id
    people类中有setDog()和setCat() 方法 所以自动装配会去找<bean.../>中id为 dog 或者cat的对象
    -->
    <bean id="people" class="com.kuang.pojo.People" autowire="byName">
        <property name="name" value="zhangsan"/>
    </bean>

7.3 byType自动装配

    <!-- 
     autowire="byType" 自动在容器上下文中查找 和自己对象set方法后面的类型对应的id   
     要保证类型全局唯一  甚至可以省略ID 因为他按类型来的
    -->
    <bean id="people" class="com.kuang.pojo.People" autowire="byType">
        <property name="name" value="zhangsan"/>

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

7.4 使用注解实现自动装配

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

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

使用注解须知

1.导入约束 context约束

2.配置注解的支持

 <context:annotation-config/>

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"
    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(在开发中最常用) 这个与java原生注解 @Resource差不多

默认使用byType方式(id可以为空),如果多个bean的类型一样就是用byName方式

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

使用@Autowired在属性上注解时就可以不再使用set方法了,前提是这个自动装备的属性在IOC容器中存在

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

@Autowired与**@Resource**的区别

@Autowire 默认按照类型装配,默认情况下它要求依赖对象必须存在如果允许为null,可以设置它required属性为false,如果我们想使用按照名称装配,可以结合@Qualifier注解一起使用

@Resource默认按照名称装配,当找不到与名称匹配的bean才会按照类型装配,可以通过name属性指定,如果没有指定name属性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找 依赖对象.注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖的对象时候,会回退到按照类型装配,但一旦指定了name属性,就只能按照名称装配了.
链接:https://www.zhihu.com/question/39356740/answer/80926247

@Nullable: 字段可以为空且不会报错

//People类的构造函数
public People( @Nullable String name) {
     this.name = name;
}

@Autowired(required = false)

如果显示的定义了Autowired的require属性为false,说明这个对象可以为null,否则不允许为空

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

@Qualifier(value = “某个id的具体值”) 这个与java原生注解 @Resource(name = “cat1001”)

//People类
public class People {
    @Autowired
    @Qualifier(value = "cat1001")//指定寻找一个id=cat1001的Cat类型对象
    private Cat cat;
    @Autowired
    private Dog dog;
<!--beans.xml文件-->
    <bean  class="com.kuang.pojo.Cat"/>
    <bean  id="cat1001" class="com.kuang.pojo.Cat"/>  <!--通过@Qualifier就指定了这个对象-->
    <bean  id="cat" class="com.kuang.pojo.Cat"/>

8、Spring使用注解开发

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

在这里插入图片描述
在使用注解需要倒入context约束以增加对注解的支持

1.bean(application.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: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">
    <!--spring注解驱动-->
    <context:annotation-config/>
    <!--扫描指定目录com.kuang.pojo包下的注解,使包下的注解生效-->
    <context:component-scan base-package="com.kuang.pojo"/>
</beans>
2.属性如何注入
/**在这个包被扫描的情况下
 *@Component 等价于<bean id="user" calss = ".....">
 * @Component  中文意思就是组件,这个注解放在类上,说明这个类被Spring管理了,就是一个bean,id是类名小写
 */
@Component
public class User {
	//相当于<property name = "name"  value = "uzi"/>,用在set方法上也行
    @Value("uzi")
    public String name;
    public void setName(String name) {this.name = name;}
}
3.衍生的注解

@Component 有几个衍生注解,一般按mvc结构分为三层

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

以上四个功能都是一样的,都是代表将某个类注册到Spring容器中,也就是装配bean

就做了一个事情:注册bean!

4.自动装配配置
  • @Autowired :自动装配通过类型。名字如果Autowi red不能唯- -自动装配上属性,则需要通过@Qualifier(va1ue=“xxx”)
  • @Nu11able字段标记了这个注解,说明这个字段可以为null;
  • @Resource:自动装配通过名字。类型。
5.作用域
@Component
@Scope("singleton")//单例模式
public class User {
    
}
6.小结

xml与注解:

xml更加万能,适用于任何场合,维护简单方便

注解:不是自己的类使用不了,维护相对复杂

xml一般用来管理bean,注解用来实现属性注入

要让注解生效必须开启注解支持

<context:annotation-config/>
<context:component-scan base-package="com.kuang.pojo"/>

9、使用Java的方式配置spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig是Spring的一个子项目,在Spring 4之后,它成为了一个核心功能!
在这里插入图片描述

User类

//@Component 表示这个类被spring接管了
@Component
public class User {
    @Value("zhangsan")
    private String name;

    @Override
    public String toString() {return ....}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

配置类KuangConfig

//@Configuration 也会被注册到容器中,因为他本来就是一个Component
//@Configuration 的意思代表这是一个配置类,这就和我们之前看的beans.xml一样的
@Configuration
@ComponentScan("com.kuang.pojo")
@Import(KuangConfig02.class)//导入其他配置类
public class KuangConfig {
    /**
     * 注册一个bean就相当于我们之前写的一个bean标签
     * id就是这个方法的名字,就相当于bean标签中的id属性
     * 这个方法的返回值就相当于bean标签中的class属性
     * @return 返回要注入到bean中的对象
     */
    @Bean
    public User getUser1001(){
        return new User();
    }
}

配置类KuangConfig02

@Configuration
@ComponentScan("com.kuang.pojo")
public class KuangConfig02 {
	//这个配置类被上面那个配置类导入了
}

测试类

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象来加载
       ApplicationContext context = new    AnnotationConfigApplicationContext(KuangConfig.class);
        User user = context.getBean("getUser1001", User.class);//getUser1001 是方法名  user是这个方法名返回的值
        System.out.println(user.getName());
    }
}

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

10、代理模式

为什么要学习代理模式?因为这就是spring AOP的底层!-【SpringAOP 和 SpringMVC重点】

代理模式的分类:

  • 静态代理
  • 动态代理
    在这里插入图片描述

10.1、静态代理

角色分析

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

代码步骤:

1、接口

//这是一个租房的接口
public interface Rent {
    //出租房屋的方法
    public void rent();
}

2、真实角色

//房东,真实角色,实现租房的接口,实现租房的方法
public class Host implements Rent{
    //房东出租房子
    public void rent() {
        System.out.println("房东出租房子");
    }
}

3、代理角色

public class Proxy implements Rent {
    private Host host;
    public Proxy() {}
    public Proxy(Host host) {this.host = host;}
    //代理帮房东出租房子
    public void rent() {
        System.out.println("代理====");
        host.rent();
    }
    //代理看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }
    //代理收中介费、签合同
    public void doOthers(){
        System.out.println("做一些其他的事情。。。");
    }
}

4、客户端访问代理角色

//模拟真实的租客要租房子
public class Client {
    public static void main(String[] args) {
        //有个房东想出租房子
        Host host = new Host();
        //中介把房东的资源拿进来,然后还可以做一些附属操作例如收差价等
        Proxy proxy = new Proxy(host);
        //所以你不用面对房东,中介直接租给你
        proxy.rent();
    }
}

代理模式的好处

  • 可以使真实角色的操作更加纯粹,不用关注一些公共业务

  • 公共业务就交给了代理角色,实现了业务的分工。

  • 公共业务发生拓展的时候方便集中管理

    缺点

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

10.2、加深理解静态代理模式

代码在spring-08

初识AOP,面向切面编程
在这里插入图片描述

10.3、动态代理

  • 动态代理静态代理角色一样(抽象角色,真实角色,代理角色)
  • 动态代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类,一类是基于接口的动态代理,另一是基于类的动态代理
    • 基于接口—JDK动态代理【主要学这个】
    • 基于类:cglib
    • Java字节码实现:javasist

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

11、AOP

11.1、什么是AOP

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

在这里插入图片描述

11.2、spring在AOP中的作用

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

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

在这里插入图片描述

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

在这里插入图片描述
即Aop在不改变原有代码的情况下,去增加新的功能。

11.3、使用spring实现AOP

【重点】使用AOP要先导入一个依赖包

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>
部署测试环境

通用的类和接口

IUserService接口

public interface IUserService {
    public void add();
}

IUserService接口的实现类UserServiceImpl

public class UserServiceImpl implements IUserService{
    public void add() {
        System.out.println("add one");
    }
}
方式一:使用spring的API接口

log日志类

public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //objects:参数
    //target:目标对象
    public void before(Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "这个类的" + method.getName() + "被执行了");
    }
}

AfterLog日志类

public class AfterLog implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
        System.out.println("执行了方法" + method.getName() + "返回的结果为" + returnValue);
    }
}

applicationContex.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.kuang.service.UserServiceImpl"/>
    <bean id="log" class="com.kuang.log.Log"/>
    <bean id="adterLog" class="com.kuang.log.AfterLog"/>
    <!--方式一:使用原生的spring api接口-->
    <!--配置aop 需要导入aop的约束-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="adterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

测试类

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

        //动态代理的是接口,所以这里返回的是接口类型
        IUserService userService = (IUserService) context.getBean("userService");

        userService.add();
    }
}
方式二:自定义类实现

自定义的类作为切面

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

applicationContext.xml

<!--注册bean-->
<bean id="userService" class="com.kuang.service.UserServiceImpl"/>
<bean id="log" class="com.kuang.log.Log"/>
<bean id="adterLog" class="com.kuang.log.AfterLog"/>

<!--方式二:注册自定义bean-->
<bean id="diy" class="com.kuang.diy.DiyPointCut"/>

<aop:config>
    <!--自定义切面,ref要引用的类-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
        <!--通知-->
        <aop:before method="before" pointcut-ref="pointcut"/>
        <aop:after method="after" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

测试类

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

        //动态代理的是接口,所以这里返回的是接口类型
        IUserService userService = (IUserService) context.getBean("userService");

        userService.add();
    }
}
方式三:使用注解实现

切面类

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

//@Aspect 标注这个类是一个切面,注意导包不要导错
@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("注解====在方法前===");
    }
}

applicationContext.xml

<!--注册bean-->
<bean id="userService" class="com.kuang.service.UserServiceImpl"/>
<bean id="log" class="com.kuang.log.Log"/>
<bean id="adterLog" class="com.kuang.log.AfterLog"/>

<!--方式三:注册一个注解bean-->
<bean id="annotationPointCut" class="com.kuang.diy.AnnotationPointCut"/>
<!--开启注解支持  默认JDK实现    cglib是另一种实现方式,一般不用-->
<aop:aspectj-autoproxy/>

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口,所以这里返回的是接口类型
        IUserService userService = (IUserService) context.getBean("userService");
        userService.select();
    }
}

12、整合mybatis

mybatis的视频还没看,先放着

13、声明式事务

1、回顾事务
  • 把一组业务当成一个业务来做,要么同时成功要么同时失败
  • 在项目的开发中你事务十分重要,涉及到数据的一致性问题
  • 确保完整性和一致性

事务的ACID原则

  • A Atomicity 原子性
    • 一个事务的所有系列操作步骤被看成一个动作,所有的步骤要么全部完成,要么一个也不会完成。如果在事务过程中发生错误,则会回滚到事务开始前的状态,将要被改变的数据库记录不会被改变。
  • C Consistency 一致性
    • 一致性是指在事务开始之前和事务结束以后,数据库的完整性约束没有被破坏,即数据库事务不能破坏关系数据的完整性及业务逻辑上的一致性。
  • I Isolation 隔离性
    • 主要用于实现并发控制,隔离能够确保并发执行的事务按顺序一个接一个地执行。通过隔离,一个未完成事务不会影响另外一个未完成事务。防止数据损坏
  • D Durability 持久性
    • 一旦一个事务被提交,它应该持久保存,不会因为与其他操作冲突而取消这个事务。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值