尚硅谷spring笔记

Spring框架介绍

  1. Spring是一个轻量开源的JavaEE的框架

  2. Spring框架可以解决企业应用开发的复杂性

  3. Spring中的两个核心:IOC和AOP

    (1)IOC:控制反转,把创建对象过程交给spring进行管理

    (2)AOP:面相切面,不修改源代码的情况下进行功能增强

  4. Spring特点

    • 方便解耦,简化开发
    • Aop编程支持
    • 方便程序测试
    • 方便和其他框架进行整合
    • 方便进行事务操作
    • 降低API开发难度

实例

编写一个User类,之后使用Spring配置文件的方式创建对象

配置文件创建方法 右键src目录->new->XML Configuration file->spring config

bean1.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="user" class="com.hty.User"></bean>
</beans>

id是为这个类起的别名,class就是类路径

User类

package com.hty;

public class User {
    public void add(){
        System.out.println("add.....");
    }
}

创建test类来进行测试

@Test
public void test(){
    //加载spring配置文件  ClassPath表示是类路径  由于是在src下 所以直接写名字就行
    ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    Book book = context.getBean("book", Book.class);//“book”这个参数就是在xml中的别名
    System.out.println(book);
}

IOC容器

IOC概念和原理

  1. 控制反转:把对象创建和对象之间的调用过程交给spring进行管理
  2. 使用IOC的目的是为了让耦合度降低
  3. 上面的案例就是IOC的实现

底层原理

xml解析、工厂模式、反射

当我们有类A和类B,要让A调用B的方法,使用javase中的知识,需要在A中newB然后调方法,这样做的耦合度太高,我们选择使用工厂模式来解耦合

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dK2BoaHA-1645190425527)(E:\编程\spring\尚硅谷\spring笔记.assets\image-20220114140125775.png)]

用IOC来解耦合

  1. xml配置文件,配置创建的对象
  2. 有service类和user类,创建工厂类
class UserFactory{
    public static User getDao(){
        String classValue = class属性值;//xml解析
        //通过反射创建对象
        Class clazz = Class.forName(classValue);
        //创建对象
        return (User)clazz.newInstance();
    }
}

IOC接口

1.IOC思想基于IOC容器完成,IOC容器底层就是对象工厂

2.spring提供IOC容器实现的两种方式(两个接口)

​ (1)BeanFactory:IOC容器基本实现,是spring内部的使用接口,不提供开发人员进行使用

​ (2)ApplicationContext:BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用

3.两个接口的区别:

​ BeanFactory:加载配置文件的时候不会创建对象,在获取对象时才去创建对象

​ ApplicationContext:在加载配置文件的时候就会把再配置文件中的对象创建

4.ApplicationContext接口的实现类

​ FileSystemXmlApplicationContext();写的是xml文件的系统路径

​ ClassPathXmlApplicationContext();写的是xml文件的类路径

IOC操作

Bean管理

(1)Spring创建对象

(2)Spring注入属性,给类的属性赋值

Bean管理操作的实现方式

(1)基于xml配置文件方式实现

(2)基于注解方式实现

基于xml配置文件方式实现

创建对象
<bean id="user" class="com.hty.User"></bean>

在spring的xml中使用bean标签,标签中添加对应的属性,就可以实现对象的创建

在bean标签中有很多属性

id属性:唯一表示

class属性:类全路径

创建对象时,默认执行无参构造,若没有则会报错

注入属性

DI:依赖注入,就是注入属性

方式一:set方法

例:

Book类

package com.hty;

public class Book {
    private String bname;
    private String bauthor;
    private String address;

    public void setBname(String bname) {
        this.bname = bname;
    }

    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "bname='" + bname + '\'' +
                ", bauthor='" + bauthor + '\'' +
                ", 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="book" class="com.hty.Book">
        <!--bean标签中使用property完成属性注入-->
        <property name="bname" value="1"></property>
        <property name="bauthor" value="1"></property>
    </bean>
</beans>
方式二:有参构造注入

Orders类

package com.hty;

public class Orders {
    private String oname;
    private String address;

    public Orders(String oname, String address) {
        this.oname = oname;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "oname='" + oname + '\'' +
                ", 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="orders" class="com.hty.Orders">
        <constructor-arg name="oname" value="1"></constructor-arg>
        <constructor-arg name="address" value="1"></constructor-arg>
    </bean>
</beans>

此时调用的就不是无参构造了,用的是有参构造

方式二的另一种写法是

<constructor-arg index="0" value="1"></constructor-arg>

这样表示的就是将构造函数中第0个元素进行赋值

方式三:对set赋值的简化—p名称空间注入

首先在beans标签中加入一个约束

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/p http://www.springframework.org/schema/p/spring-p.xsd">
    <bean id="book" class="com.hty.Book" p:bname="1" p:bauthor="1"></bean>
</beans>
Xml方式注入字面量

1.null值

<?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="book" class="com.hty.Book">
        <!--bean标签中使用property完成属性注入-->
        <property name="bname" value="1"></property>
        <property name="bauthor" value="1"></property>
<!--        设置null值-->
        <property name="address">
            <null/>
        </property>
    </bean>
</beans>

2.属性值中有特殊符号

方法一:使用&It;&gt;进行转义

方法二:写在CDATA中

<?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="book" class="com.hty.Book">
        <!--bean标签中使用property完成属性注入-->
        <property name="bname" value="1"></property>
        <property name="bauthor" value="1"></property>
<!--        属性值包含特殊符号 有可能将尖括号识别为一个标签-->
        <property name="address">
            <value><![CDATA[<<南京>>]]></value>
        </property>
    </bean>
</beans>

其中<<南京>>就是属性值

注入属性-----外部bean

创建service和dao类,service中调用dao类,此时我们注入的就是一个自定义对象,使用set方式注入

dao类

package com.dao;

public interface UserDao {
    public void update();
}
package com.dao;

import com.hty.User;

public class UserDaoImpl implements UserDao{

    @Override
    public void update() {
        System.out.println("dao update.........");
    }
}

service类

package com.service;

import com.dao.UserDao;

public class UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add(){
        System.out.println("add.......");
        userDao.update();
    }
}

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="userService" class="com.service.UserService">
        <property name="userDao" ref="userDao"></property>   ref标签是要调用的类的bean标签的id
    </bean>
    <bean id="userDao" class="com.dao.UserDaoImpl"></bean>
</beans>
注入属性-----内部bean

一对多的关系:部门与员工

部门类

package com.bean;

public class Dept {
    private String dname;



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

    public void setDname(String dname) {
        this.dname = dname;
    }
}

员工类

package com.bean;

public class Emp {
    private String ename;
    private String gender;
    //员工属于某一个部门
    private Dept dept;

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "ename='" + ename + '\'' +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

xml文件使用内部bean

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

    <bean id="emp" class="com.bean.Emp">
        <property name="ename" value="1"></property>
        <property name="gender" value=""></property>
        <property name="dept">
            <!--内部使用bean-->
            <bean id="dept" class="com.bean.Dept">
                <property name="dname" value="安保"></property>
            </bean>
        </property>
    </bean>
</beans>
级联赋值

以上的过程其实就是一种级联赋值

另一种是外部bean的级联赋值

<?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="emp" class="com.bean.Emp">
        <property name="ename" value="1"></property>
        <property name="gender" value=""></property>
        <property name="dept" ref="dept"></property>
        <property name="dept.dname" value="财务"></property>
    </bean>
    <bean id="dept" class="com.bean.Dept"></bean>
</beans>

注:我们使用了dept的dname属性代表要获取这个对象,要在Emp类中写出一个get方法才能获取到对象

xml注入集合属性
  1. 注入数组类型属性
  2. 注入List集合
  3. 注入map集合
  4. 注入set集合

案例:

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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="stu" class="com.hty.spring5.collectiontype.Stu">
        <!--数组类型注入-->
        <property name="courses">
            <array>
                <value>java</value>
                <value>mysql</value>
            </array>
        </property>
        <!--list集合-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>李四</value>
            </list>
        </property>
        <!--map集合-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--set集合-->
        <property name="sets">
            <set>
                <value>mysql</value>
                <value>redis</value>
            </set>
        </property>
        <!--list集合中是一个对象-->
        <property name="courseList">
            <list>
                <ref bean="course"></ref>
            </list>
        </property>
    </bean>
    <bean id="course" class="com.hty.spring5.collectiontype.Course">
        <property name="cname" value="1"></property>
    </bean>
</beans>

优化:将集合注入部分提取出来,作为公共部分可以让其他类使用

(1)在xml文件中引入util名称空间

(2)使用util标签完成list集合注入提取

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <util:list id="courseList">
        <value>java</value>
        <value>html</value>
        <value>mysql</value>
    </util:list>
    <bean id="courses" class="com.hty.spring5.collectiontype.Courses">
        <property name="courselists" ref="courseList"></property>
    </bean>
</beans>
FactoryBean

普通bean:在配置文件中定义bean类型就是返回类型

工厂bean:在配置文件中定义bean类型可以和返回类型不一样

(1)创建类MyBean实现接口FactoryBean

(2)实现接口里面的方法,在实现的方法中定义返回的bean类型

package com.hty.spring5.facbean;

import com.hty.spring5.collectiontype.Course;
import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {
    //定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("123");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

代码中重点是getObject()方法,这个方法的返回类型就是最后测试代码中的返回值

测试代码中 getBean(“工厂Bean的id”,返回值类型.class);

Bean的作用域

1.在spring中设置创建bean实例是单实例还是多实例

2.在spring中的默认情况下,bean是单实例

若是单实例,那么我们在测试代码中获取两次bean之后会发现是同一个类

设置多实例方法

在spring配置文件bean标签里面有一个属性scope属性用于设置实例

scope属性值

​ singleton:单实例

​ prototype:多实例

Bean的生命周期

1.无参构造创建bean实例

2.为bean的属性设置值

3.把bean实例传递给bean后置处理器的方法PostProcessBeforeInitialization

4.调用bena的初始化的方法(需要配置)[init-method属性]

5.把bean实例传递给bean后置处理器的方法PostProcessAfterInitialization

6.bean的使用

7.容器关闭时候,调用bean销毁的方法(要配置)之后再测试类中调用context.close()方法

注:context需要强转为ClassPathXmlApplicationContext类型

创建类的时候实现BeanPostProcessor接口,创建后置处理器

后置处理器也需要配置

案例:

Orders类

package com.hty.spring5.bean;

public class Orders {

    private String oname;

    public Orders() {
        System.out.println("第一步 执行无参构造创建了bean实例");
    }

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用set方法进行赋值");
    }

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

    public void initMethod(){
        System.out.println("第三步 执行初始化方法");
    }

    public void destroyMethod(){
        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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="orders" class="com.hty.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="1"></property>
    </bean>
</beans>

测试类

package com.hty.spring5.test;

import com.hty.spring5.bean.Orders;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步 获取到bean实例");
        System.out.println(orders);
        ((ClassPathXmlApplicationContext) context).close();
    }
}
xml自动装配(一般使用注解进行)

自动装配:根据指定装配规则(属性名称或者属性类型),spring自动将匹配的属性值进行注入

xml文件中的bean标签有属性叫autowire,属性值为byName和byType

案例:

Dept类

package com.hty.spring5.autowire;

public class Dept {
    @Override
    public String toString() {
        return "Dept{}";
    }
}

Emp类

package com.hty.spring5.autowire;

public class Emp {
    private Dept dept;

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "dept=" + dept +
                '}';
    }
}

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="emp" class="com.hty.spring5.autowire.Emp" autowire="byName"></bean>
    <bean id="dept" class="com.hty.spring5.autowire.Dept"></bean>
</beans>
外部属性文件

1.先创建properties配置文件

prop.driverClass=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
prop.userName=root
prop.password=123456

左边的属性名可以任意

2.移入到spring的xml中

首先引入context名称空间

3.使用标签引入

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

    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>
</beans>

使用注解方式

注解是代码特殊标记,格式为@注解名(属性名=属性值…)

使用注解可以简化xml配置

(1)@Component

(2)@Service

(3)@Controller

(4)@Repository

上面四个注解本质没有区别,只是放在不同类型的类上面作为标记

创建对象

1.引入spring-aop jar包

2.开启组件扫描

首先引入context名称空间

在base-package后面加上user-default-filters="false"表示现在不是用默认filter,自己配置filter

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.hty.spring5" user-default-filters="false"></context:component-scan>

</beans>

context这个标签下有一个子标签

<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

用来设置扫描哪些内容

annotation代表扫描注解,后面的路径表示只扫描带有这个包下注解的类

当不写user-default-filters是表示不扫描带这个注解的类

3.创建类,在类上面添加创建对象注解

@Component(value=“…”)后面写的是bean中的id属性,可省略,默认为类名的首字母小写

注解实现属性注入

(1)@Autowired:根据属性类型自动装配

把service和dao利用注解创建对象

在service中注入对象,在service类添加dao类型属性,在属性上面使用注解即可

service类

package com.hty.spring5.service;

import com.hty.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public void add(){
        System.out.println("Service add.....");
        userDao.add();
    }
}

Dao接口

package com.hty.spring5.dao;

public interface UserDao {
    public void add();

}

Dao接口实现类

package com.hty.spring5.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao{
    @Override
    public void add() {
        System.out.println("dao add.......");
    }
}

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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.hty.spring5"></context:component-scan>
</beans>

(2)@Qualifier:根据属性名称进行注入

这个注解要和Autowired在一起使用,在Autowired下加@Qualifier(value=“”),这个value写的就是要注入的类上面注解后面的value

(3)@Resource:可以根据类型/名称注入

(4)@Value:注入普通类型属性

完全注解开发,不需要配置文件
  1. 创建配置类

    在配置类上加注解@Configration(basePackage={“要扫描的包路径”});

  2. 测试类中将ClassPathXmlApplicationContext(配置类名.class);

AOP

基本概念

面向切面/方面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之前的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

底层原理

AOP底层使用的是动态代理,有两种情况的动态代理

1.有接口的情况,使用JDK动态代理创建接口实现类代理对象,增强类的方法

2.没有接口的情况,使用CGLIB动态代理创建子类的代理对象,增强类的方法

AOP术语

  1. 连接点

    类中哪些方法可以被增强,这些方法被称为连接点

  2. 切入点

    实际被真正增强的方法称为切入点

  3. 通知(增强)

    实际增强的逻辑部分称为通知(增强),通知有多种类型

    前置通知

    后置通知

    环绕通知

    异常通知

    最终通知

  4. 切面

    是动作,把通知应用到切入点过程

AOP准备工作

1.spring框架一般基于AspectJ实现AOP操作AspectJ不是spring组成部分,独立AOP框架,一般把AspectJ和spring框架一起使用,进行AOP操作

2.基于AspectJ实现AOP操作

​ (1)基于xml‘配置文件方式

​ (2)基于注解方式

3.在项目中引入AOP相关依赖(aspectJ)包

4.切入点表达式

作用:知道对哪个类里面的那个方法进行增强

语法:execution([权限修饰符] [返回类型] [类全路径] [方法名] ([参数]))

例:对com.hty.dao.BookDao类中的add进行增强

execution(* com.hty.dao.BookDao.add(…))

AspectJ注解

  1. 创建类,在类中定义方法

  2. 创建一个增强类

    创建方法,让不同方法代表不同通知类型

  3. 进行通知配置

    (1) 在spring配置文件中,开启注解扫描

    (2)使用注解创建User和UserProxy对象

    (3)在增强类上添加注解@Aspect

    ​ 首先加aop名称空间,然后使用标签

    <aop:aspectj-autoproxy/>

  4. 配置不同类型的通知

    在增强类中,在作为通知方法上面,添加通知类型注解,使用切入点表达式配置

    前置通知 @Before(value = “execution(* com…User.add(…))”)

    后置通知 @After()

    环绕通知 @Around 这个在方法前后都会执行

    最终通知 @AfterReturning

    异常通知 @AfterThrowing

  5. 公共切入点抽取

    @Pointcut(value = “…”)

    之后的注解只用写这个方法名加括号

  6. 有多个增强类对同一个方法进行增强,设置增强类优先级

    在增强类上面添加注解@Order(数字) 数越小优先级越高

AspectJ配置文件

  1. 创建增强类和被增强类,创建方法
  2. 在spring配置文件中创建两个类对象
  3. 在spring的xml文件中配置切入点

JDBCTemplate

spring框架对JDBC进行封装,使用JDNCTemplate方便实现对数据库操作

准备工作

引入jar包,在xml中配置数据库连接池

配置JDBCTemplate注入DateSource

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<property name="dataSource" ref="dataSource"></property>
</bean>

创建service类,创建dao类,在dao注入jdbcTemplate对象

使用模板来进行添加数据

1.创建实体类

2.编写service和dao类

​ (1)在dao进行数据库添加操作

​ (2)调用jdbcTemplate的update方法实现添加操作

案例

Dao接口

package com.hty.spring5.dao;


import com.hty.spring5.entity.Book;

import java.util.List;

public interface BookDao {
    void add(Book book);

    void updateBook(Book book);

    void deleteBook(String id);

    int selectCount();

    Book findBookInfo(String id);

    List<Book> findAllBook();

    void batchAllBook(List<Object[]> batchArgs);

    void batchUpdateBook(List<Object[]> batchArgs);

    void batchDeleteBook(List<Object[]> batchArgs);
}

Dao接口实现类

package com.hty.spring5.dao;

import com.hty.spring5.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao{
    //注入jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(Book book) {
        String sql = "insert into t_book values(?,?,?)";
        int update = jdbcTemplate.update(sql, book.getUserId(), book.getUserName(), book.getUstatus());
        System.out.println(update);
    }

    @Override
    public void updateBook(Book book) {
        String sql = "update t_book set username=?,ustatus=? where user_id=?";
        int update = jdbcTemplate.update(sql, book.getUserName(), book.getUstatus(), book.getUserId());
        System.out.println(update);
    }

    @Override
    public void deleteBook(String id) {
        String sql = "delete from t_book where user_id=?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    @Override
    public int selectCount() {
        String sql = "select count(*) from t_book";
        Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
        return integer;
    }

    @Override
    public Book findBookInfo(String id) {
        String sql = "select * from t_book where user_id = ?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        return book;
    }

    @Override
    public List<Book> findAllBook() {
        String sql = "select * from t_book";
        List<Book> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return query;
    }

    @Override
    public void batchAllBook(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchUpdateBook(List<Object[]> batchArgs) {
        String sql = "update t_book set username=?,ustatus=? where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchDeleteBook(List<Object[]> batchArgs) {
        String sql = "delete from t_book where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}

实体类

package com.hty.spring5.entity;

public class Book {
    private String userId;
    private String userName;
    private String ustatus;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUstatus() {
        return ustatus;
    }

    public void setUstatus(String ustatus) {
        this.ustatus = ustatus;
    }

    @Override
    public String toString() {
        return "Book{" +
                "userId='" + userId + '\'' +
                ", userName='" + userName + '\'' +
                ", ustatus='" + ustatus + '\'' +
                '}';
    }
}

service类

package com.hty.spring5.service;

import com.hty.spring5.dao.BookDao;
import com.hty.spring5.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    //注入dao
    @Autowired
    private BookDao bookDao;

    //添加
    public void addBook(Book book){
        bookDao.add(book);
    }
    //修改
    public void update(Book book){
        bookDao.updateBook(book);
    }
    //删除
    public void delete(String id){
        bookDao.deleteBook(id);
    }
    //查询表的记录数
    public int findCount(){
        return bookDao.selectCount();
    }
    //查询返回一个对象
    public Book findOne(String id){
        return bookDao.findBookInfo(id);
    }
    //查询所有的信息
    public List<Book> findAll(){
        return bookDao.findAllBook();
    }
    //批量插入数据
    public void batchAll(List<Object[]> batchArgs){
        bookDao.batchAllBook(batchArgs);
    }
    //批量修改数据
    public void batcUpdate(List<Object[]> batchArgs){
        bookDao.batchUpdateBook(batchArgs);
    }
    //批量删除数据
    public void batchDelete(List<Object[]> batchArgs){
        bookDao.batchDeleteBook(batchArgs);
    }
}

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 http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/user_db?serverTimezone=Asia/Shanghai"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启组件扫描-->
    <context:component-scan base-package="com.hty.spring5"></context:component-scan>
</beans>

测试类

package com.hty.spring5.test;

import com.hty.spring5.entity.Book;
import com.hty.spring5.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class Test1 {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
//        Book book = new Book();
//        book.setUserId("2");
//        book.setUserName("1");
//        book.setUstatus("1");
//        bookService.addBook(book);
//        bookService.update(book);
//        bookService.delete("1");
//        int count = bookService.findCount();
//        System.out.println(count);
//        Book one = bookService.findOne("2");
//        System.out.println(one);
//        List<Book> all = bookService.findAll();
//        for (Book book : all) {
//            System.out.println(book);
//        }
//        List<Object[]> l = new ArrayList<>();
//        Object[] o1 = {"3","3","3"};
//        Object[] o2 = {"4","4","4"};
//        Object[] o3 = {"5","5","5"};
//        l.add(o1);
//        l.add(o2);
//        l.add(o3);
//        bookService.batchAll(l);

//        List<Object[]> l = new ArrayList<>();
//        Object[] o1 = {"3","3","2"};
//        Object[] o2 = {"4","4","3"};
//        Object[] o3 = {"5","5","4"};
//        l.add(o1);
//        l.add(o2);
//        l.add(o3);
//        bookService.batcUpdate(l);

        List<Object[]> l = new ArrayList<>();
        Object[] o1 = {"3"};
        Object[] o2 = {"4"};
        Object[] o3 = {"5"};
        l.add(o1);
        l.add(o2);
        l.add(o3);
        bookService.batchDelete(l);
    }
}

事务操作

事务是数据库操作最基本单元,逻辑上一组操作要么都成功,如果有一个失败所有操作都失败

事务四个特性(ACID)

(1)原子性

(2)一致性

(3)隔离性

(4)持久性

搭建案例环境

Dao接口

package com.hty.spring5.dao;

public interface UserDao {

    public void addMoney();

    public void reduceMoney();
}

Dao接口实现类

package com.hty.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //lucy转账100给mary
    @Override
    public void addMoney() {
        String sql = "update t_account set money = money-? where username = ?";
        jdbcTemplate.update(sql,100,"lucy");
    }

    @Override
    public void reduceMoney() {
        String sql = "update t_account set money = money+? where username = ?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

service类

package com.hty.spring5.service;

import com.hty.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney(){
        userDao.reduceMoney();
        userDao.addMoney();
    }
}

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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://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="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/user_db?serverTimezone=Asia/Shanghai"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启组件扫描-->
    <context:component-scan base-package="com.hty.spring5"></context:component-scan>
    <!--创建事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

spring事务管理介绍

  1. 事务一般添加在service层中(业务逻辑层)

  2. 操作方式有两种

    -编程式事务操作 需要写代码

    -声明式事务操作(常用) 需要进行配置

Spring事务管理API

提供了一个接口,代表事务管理器,这接口针对不同的框架提供不同的实现类(PlatformTransactionManager接口)

声明式事务管理

(1)基于注解方式(常用)

(2)基于xml方式

底层使用到了AOP原理

注解方式
  1. 在spring配置文件中配置事务管理器

    <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
  2. 在spring配置文件中,开启事务注解

    在spring配置文件中引入 tx名称空间

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

    开启事务注解

    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    
  3. 在service类上(或service类里面方法上面)添加事务注解(Transactional)

    把注解添加到类上,表示这个类的所有方法都添加事务

    把注解添加到方法上,表示只有这个类添加了事务

service类

package com.hty.spring5.service;

import com.hty.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserService {
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney(){
        //使用try catch就是编程式事务操作
//        try{
            //开启事务操作

            //进行业务操作
            userDao.reduceMoney();
            //模拟异常
            int a = 10/0;
            userDao.addMoney();
            //没有发生异常 提交事务
//        }catch (Exception e){
            //出现异常 事务回滚
//        }
    }
}

Dao接口

package com.hty.spring5.dao;

public interface UserDao {

    public void addMoney();

    public void reduceMoney();
}

Dao实现类

package com.hty.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //lucy转账100给mary
    @Override
    public void addMoney() {
        String sql = "update t_account set money = money-? where username = ?";
        jdbcTemplate.update(sql,100,"lucy");
    }

    @Override
    public void reduceMoney() {
        String sql = "update t_account set money = money+? where username = ?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://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="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/user_db?serverTimezone=Asia/Shanghai"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启组件扫描-->
    <context:component-scan base-package="com.hty.spring5"></context:component-scan>
    <!--创建事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
@Transactional注解的参数配置

在service类上添加注解@Transactional,在这个注解里面,可以配置事务相关参数

propagation:事务传播行为

多事务方法之间进行调用,这个过程中事务是如何进行管理的

事务方法:对数据库表数据进行变化的操作(增删改)

Spring框架事务传播行为有7种

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZzKCjzJA-1645190425529)(E:\编程\spring\尚硅谷\spring笔记.assets\image-20220115125546513.png)]

创建两个方法

@Transactional
public void add(){
    //调用update
    update();
}
public void update(){}

REQUIRED:若add方法本身有事务,调用update方法之后,update使用当前add方法里面事务

​ 若add方法本身没有事务,调用update方法之后,创建新事务

REQUIRED_NEW:使用add方法调用update方法,如果add无论是否有事务,都创建新的事务

isolation:事务隔离级别

事务有特性称为隔离性:多事务操作之间不会产生影响,不考虑隔离性会产生三个读问题:脏读,不可重复读,虚(幻)读

脏读:一个未提交事务读取到另一个未提交事务的数据

不可重复读:一个未提交事务读取到另一提交事务修改数据

虚读:一个未提交事务读取到另一提交事务添加数据

通过设置事务隔离级别,解决读的问题

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6s4EvGji-1645190425529)(E:\编程\spring\尚硅谷\spring笔记.assets\image-20220115132506944.png)]

timeout:超时时间

事务需要在一定时间内进行提交,如果不提交会进行回滚

spring的默认值为-1(不超时) 设置时间以秒为单位计算

readOnly:是否只读

读:查询操作,写:添加修改删除操作

readOnly默认值false,表示可以查询,可以添加修改删除

设置值为true,只能查询

rollbackFor:回滚

设置查询哪些异常进行事务回滚

noRollbackFor:不回滚

设置查询哪些异常不进行事务回滚

XML方式

在spring配置文件中进行配置

配置事务管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

配置通知

<!--配置通知-->
<tx:advice id="txadvice">
    <!--配置事务参数-->
    <tx:attributes>
        <!--指定哪种规则的方法上面添加事务-->
        <tx:method name="accountMoney" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

配置切入点和切面

<!--配置切入点和切面-->
<aop:config>
    <!--配置切入点-->
    <aop:pointcut id="pt" expression="execution(* com.hty.spring5.service.UserService.*(..))"/>
    <!--配置切面-->
    <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
完全注解开发

创建配置类,使用配置类代替xml配置文件

package com.hty.spring5.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration//配置类
@ComponentScan(basePackages = "com.hty")//开启组件扫描
@EnableTransactionManagement//开启事务
public class TxConfig {
    //创建数据库的连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/user_db?serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
    //创建jdbc模板对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值