Spring知识点--还没写完

Spring-尚硅谷

Spring5框架

课程内容介绍:

1、Spring概念

2、IOC容器

3、AOP

4、JDBCTemplate

5、事务管理

5、Spring5新特性

一、概念

必须记住:

Spring框架是一个轻量级的开源的javaee框架

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

Spring有两个核心部分:IOC、AOP

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

(2)AOp:面向切面,不修改源代码进行功能增强

1、 Spring的特点

方便解耦,简化开发;Aop变成支持;支持程序控制;方便和其他框架进行整合;方便进行事务操作。降低API开发难度

二、IOC容器

1、def

IOC控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理。

使用IOC目的:为了耦合度降低。

做入门案例就是IOC实现

2、IOC底层原理

xml解析、工厂模式、反射

3、IOC接口(BeanFactory)

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

Spring提供IOC容器实现两种实现方式。(两个接口)

(1)BeanFactory:最基本的实现,是spring内部的使用使用接口,不提供给开发人员使用。

*加载配置文件的时候不会创建对象,在使用(获取)的时候才会创建对象

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

*加载配置文件的时候就会把配置文件的对象进行创建

该接口里面有实现类

4、IOC操作Bean管理(基于xml)

1、什么是Bean管理

Spring创建对象

spring注入属性

2、Bean管理操作有两种方式:

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

<!--配置 User 对象创建--> 
 <bean id="user" class="com.atguigu.spring5.User"></bean>

在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建

在bean标签有很多属性,较少常用的属性。

id属性:唯一标识

class属性:类全路径(包类)

创建对象的时候,默认也是执行无参数构造方法。

(2)基于注解方式实现

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

第一种注入方式:使用set方法

/**
* 演示使用 set 方法进行注入属性
*/
public class Book {
 //创建属性
 private String bname;
 private String bauthor;
 //创建属性对应的 set 方法
 public void setBname(String bname) {
 this.bname = bname;
 }
 public void setBauthor(String bauthor) {
 this.bauthor = bauthor;
 }
}
(2)在 spring 配置文件配置对象创建,配置属性注入
<!--2 set 方法注入属性-->
<bean id="book" class="com.atguigu.spring5.Book">
 <!--使用 property 完成属性注入
 name:类里面属性名称
 value:向属性注入的值
 -->
 <property name="bname" value="易筋经"></property>
 <property name="bauthor" value="达摩老祖"></property>
</bean>
​

第二种:通过有参数的构造函数

(1)创建类,定义属性,创建属性对应有参数构造方法
/**
* 使用有参数构造注入
*/
public class Orders {
 //属性
 private String oname;
 private String address;
 //有参数构造
 public Orders(String oname,String address) {
 this.oname = oname;
 this.address = address;
 }
}
(2)在 spring 配置文件中进行配置
<!--3 有参数构造注入属性-->
<bean id="orders" class="com.atguigu.spring5.Orders">
 <constructor-arg name="oname" value="电脑"></constructor-arg>
 <constructor-arg name="address" value="China"></constructor-arg>
</bean>(1)创建

5、p 名称空间注入(了解)

(1)使用 p 名称空间注入,可以简化基于 xml 配置方式

第一步 添加 p 名称空间在配置文件中

第二步 进行属性注入,在 bean 标签里面进行操作

5、IOC操作Bean管理(xml 注入其他类型属性)

1、字面量:设置固定值

  • null值

<!--null 值-->
<property name="address">
 <null/>
</property>
​

  • 属性值包含特殊符号

<!--属性值包含特殊符号
 1 把<>进行转义 &lt; &gt;
 2 把带特殊符号内容写到 CDATA
-->
<property name="address">
 <value><![CDATA[<<南京>>]]></value>
</property>
​

2、注入属性-外部bean

(1)创建两个类 service 类和 dao 类
(2)在 service 调用 dao 里面的方法
(3)在 spring 配置文件中进行配置
public class UserService {
 //创建 UserDao 类型属性,生成 set 方法
 private UserDao userDao;
 public void setUserDao(UserDao userDao) {
 this.userDao = userDao;
 }
 public void add() {
 System.out.println("service add...............");
 userDao.update();
 }
}
<!--1 service 和 dao 对象创建-->
<bean id="userService" class="com.atguigu.spring5.service.UserService">
 <!--注入 userDao 对象
 name 属性:类里面属性名称
 ref 属性:创建 userDao 对象 bean 标签 id 值
 -->
 <property name="userDao" ref="userDaoImpl"></property>
</bean>
<bean id="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean>

3、注入属性-内部bean和级联赋值

(1)一对多关系:部门和员工 一个部门有多个员工,一个员工属于一个部门 部门是一,员工是多 (2)在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示

​
//部门类
public class Dept {
 private String dname;
 public void setDname(String dname) {
 this.dname = dname;
 }
}
//员工类
public class Emp {
 private String ename;
 private String gender;
 //员工属于某一个部门,使用对象形式表示
 private Dept dept;
 public void setDept(Dept dept) {
 this.dept = dept;
 }
 public void setEname(String ename) {
 this.ename = ename;
 }
 public void setGender(String gender) {
 this.gender = gender;
 }
}
(3)在 spring 配置文件中进行配置
<!--内部 bean-->
<bean id="emp" class="com.atguigu.spring5.bean.Emp">
 <!--设置两个普通属性-->
 <property name="ename" value="lucy"></property>
 <property name="gender" value="女"></property>
 <!--设置对象类型属性-->
 <property name="dept">
 <bean id="dept" class="com.atguigu.spring5.bean.Dept">
 <property name="dname" value="安保部"></property>
 </bean>
 </property>
</bean>
​

4、注入属性-级联赋值

(1)第一种写法 
<!--级联赋值-->
<bean id="emp" class="com.atguigu.spring5.bean.Emp">
 <!--设置两个普通属性-->
 <property name="ename" value="lucy"></property>
 <property name="gender" value="女"></property>
 <!--级联赋值-->
 <property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="com.atguigu.spring5.bean.Dept">
 <property name="dname" value="财务部"></property>
</bean>
(2)第二种写法
<!--级联赋值-->
<bean id="emp" class="com.atguigu.spring5.bean.Emp">
 <!--设置两个普通属性-->
 <property name="ename" value="lucy"></property>
 <property name="gender" value="女"></property>
 <!--级联赋值-->
 <property name="dept" ref="dept"></property>
 <property name="dept.dname" value="技术部"></property>
</bean>
<bean id="dept" class="com.atguigu.spring5.bean.Dept">
 <property name="dname" value="财务部"></property>
</bean>
​

5、IOC 操作 Bean 管理(xml 注入集合属性)

1、注入数组类型属性

2、注入 List 集合类型属性

3、注入 Map 集合类型属性

(1)创建类,定义数组、list、map、set 类型属性,生成对应 set 方法
public class Stu {
 //1 数组类型属性
 private String[] courses;
 //2 list 集合类型属性
 private List<String> list;
 //3 map 集合类型属性
 private Map<String,String> maps;
 //4 set 集合类型属性
 private Set<String> sets;
 public void setSets(Set<String> sets) {
 this.sets = sets;
 }
 public void setCourses(String[] courses) {
 this.courses = courses;
 }
 public void setList(List<String> list) {
 this.list = list;
 }
 public void setMaps(Map<String, String> maps) {
 this.maps = maps;
 }
}
(2)在 spring 配置文件进行配置
<!--1 集合类型属性注入-->
<bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">
 <!--数组类型属性注入-->
 <property name="courses">
 <array>
 <value>java 课程</value>
 <value>数据库课程</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>
</bean>

4、在集合里面设置对象类型值

5、把集合注入部分提取出来

4、在集合里面设置对象类型值
<!--创建多个 course 对象-->
<bean id="course1" class="com.atguigu.spring5.collectiontype.Course">
 <property name="cname" value="Spring5 框架"></property>
</bean>
<bean id="course2" class="com.atguigu.spring5.collectiontype.Course">
 <property name="cname" value="MyBatis 框架"></property>
</bean>
<!--注入 list 集合类型,值是对象-->
<property name="courseList">
 <list>
 <ref bean="course1"></ref>
 <ref bean="course2"></ref>
 </list>
</property>


5、把集合注入部分提取出来
(1)在 spring 配置文件中引入名称空间 util
<?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: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">
(2)使用 util 标签完成 list 集合注入提取
<!--1 提取 list 集合类型属性注入-->
<util:list id="bookList">
 <value>易筋经</value>
 <value>九阴真经</value>
 <value>九阳神功</value>
</util:list>
<!--2 提取 list 集合类型属性注入使用-->
<bean id="book" class="com.atguigu.spring5.collectiontype.Book">
 <property name="list" ref="bookList"></property>
</bean>

6、IOC 操作 Bean 管理(FactoryBean)

1、Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean) 2、普通 bean:在配置文件中定义 bean 类型就是返回类型 3、工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样 第一步 创建类,让这个类作为工厂 bean,实现接口 FactoryBean 第二步 实现接口里面的方法,在实现的方法中定义返回的 bean 类型

public class MyBean implements FactoryBean<Course> {
 //定义返回 bean
 @Override
 public Course getObject() throws Exception {
 Course course = new Course();
 course.setCname("abc");
 return course;
 }
 @Override
 public Class<?> getObjectType() {
 return null;
 }
 @Override
 public boolean isSingleton() {
 return false;
 }
}
<bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
</bean>
@Test
public void test3() {
 ApplicationContext context =
 new ClassPathXmlApplicationContext("bean3.xml");
 Course course = context.getBean("myBean", Course.class);
 System.out.println(course);
}

7、IOC操作Bean管理(Bean作用域)

在spring里面,设置创建bean实例是单实例还是多实例

在spring里面,默认情况下,bean是单实例对象

如何设置单实例还是多实例?

在Spring配置文件中bean标签里面有属性(scope)用于设置单实例还是多实例

scope属性值

第一个值 默认值,singleton,表示是单实例对象

第二个值 prototype,表示是多实例对象

  • singleton和prototype区别

singleton单实例,prototype多实例

设置scope值是singleton的时候,加载spring配置文件的时候就会创建单实例对象

设置scope值是prototype的时候,不是在加载spring配置文件的时候创建对象,在调用getBean方法的时候创建多实例对象

8、IOC操作Bean管理(生命周期)

1、生命周期

从对象创建到对象销毁的过程就是生命周期

2、bean生命周期

  • 通过构造器创建bean实例(无参数构造)

  • 为bean的属性设置值和对其他bean引用(调用set方法)

  • 调用bean的初始化的方法(需要进行配置)

  • bean可以使用(对象获取到了)

  • 当容器关闭的时候,调用bean的销毁的方法(需要进行配置销毁的方法

3、bean后置处理器---bean 生命周期有七步

(1)通过构造器创建 bean 实例(无参数构造) (2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法) (3)把 bean 实例传递 bean 后置处理器的方法 postProcessBeforeInitialization (4)调用 bean 的初始化的方法(需要进行配置初始化的方法) (5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization (6)bean 可以使用了(对象获取到了) (7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

 

9、IOC 操作 Bean 管理(xml 自动装配)

1、什么是自动装配

  • 根据指定抓鬼配规则(属性名称胡总和属性类型),spring自动将匹配的属性值进行注入

2、演示自动装配过程

(1)根据属性名称自动注入 <!--实现自动装配 bean 标签属性 autowire,配置自动装配 autowire 属性常用两个值: byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样 byType 根据属性类型注入 --> <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName"> <!--<property name="dept" ref="dept"></property>--> </bean> <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean> (2)根据属性类型自动注入 <!--实现自动装配 bean 标签属性 autowire,配置自动装配 autowire 属性常用两个值: byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样 byType 根据属性类型注入 --> <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType"> <!--<property name="dept" ref="dept"></property>--> </bean> <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

10、IOC 操作 Bean 管理(外部属性文件)

1、直接配置数据库信息

(1)配置德鲁伊连接池

<!--直接配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
 <property name="url" 
value="jdbc:mysql://localhost:3306/userDb"></property>
 <property name="username" value="root"></property>
 <property name="password" value="root"></property>
</bean>

2、通过引入外部属性文件配置数据库连接池

2、引入外部属性文件配置数据库连接池
(1)创建外部属性文件,properties 格式文件,写数据库信息
(2)把外部 properties 属性文件引入到 spring 配置文件中
* 引入 context 名称空间
<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: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">
⚫ 在 spring 配置文件使用标签引入外部属性文件
<!--引入外部属性文件-->
<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>

11、IOC操作Bean管理(基于注解)

1、什么是注解

注解是代码特殊表级,格式:@注解名称(属性名称=属性值,属性名称=属性值。。。)

使用注解,注解可以在什么地方用。

注解作用在类上面,方法上面,属性上面

使用注解的目的:简化xml的配置

2、spring针对bean管理中创建对象提供注解

(1)@Component

(2)@Service

(3)@Controller

(4)@Repository

*上面的四个注解功能上一样的,都可以用来创建bean实例

3、开启组件扫描

去扫描带这个注解的类Controller

<!--示例 1
 use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
 context:include-filter ,设置扫描哪些内容
-->
<context:component-scan base-package="com.atguigu" use-defaultfilters="false">
 <context:include-filter type="annotation" 
 
expression="org.springframework.stereotype.Controller"/>
</context:component-scan》

扫描不包含下面这个注解的内容

<!--示例 2
 下面配置扫描包所有内容
 context:exclude-filter: 设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.atguigu">
 <context:exclude-filter type="annotation" 
 
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

4、基于注解方式实现属性注入

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

第一步 把 service 和 dao 对象创建,在 service 和 dao 类添加创建对象注解
第二步 在 service 注入 dao 对象,在 service 类添加 dao 类型属性,在属性上面使用注解
@Service
public class UserService {
 //定义 dao 类型属性
 //不需要添加 set 方法
 //添加注入属性注解
 @Autowired 
 private UserDao userDao;
 public void add() {
 System.out.println("service add.......");
 userDao.add();
 }
}

(2)@Qualifier:根据名称进行注入,当有多个实现类的时候,名称就指定哪一个实现类

这个@Qualifier 注解的使用,和上面@Autowired 一起使用
//定义 dao 类型属性
//不需要添加 set 方法
//添加注入属性注解
@Autowired //根据类型进行注入
@Qualifier(value = "userDaoImpl1") //根据名称进行注入
private UserDao userDao;

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

//@Resource //根据类型进行注入
@Resource(name = "userDaoImpl1") //根据名称进行注入
private UserDao userDao;

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

@Value(value = "abc")
private String name;

5、完全注解开发

(1)创建配置类,替代 xml 配置文件

@Configuration //作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {
}

(2)编写测试类

@Test
public void testService2() {
 //加载配置类
 ApplicationContext context
 = new AnnotationConfigApplicationContext(SpringConfig.class);
 UserService userService = context.getBean("userService", 
UserService.class);
 System.out.println(userService);
 userService.add();
}

三、AOP:面向切面,不修改源代码进行功能增强

1、什么是AOP?

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

通俗解释:不通过修改源代码,在主干功能里面添加新功能。

2、AOP底层原理

1、AOP底层使用动态代理

(1)有两种情况动态代理

第一种:有接口的情况,使用JDK动态代理

创建UserDao接口实现类代理对象,增强类的方法。

第二种:没有接口情况,使用CGLIB动态代理

创建当前类子类的代理对象

3、AOP(JDK动态代理)

1、使用JDK动态代理,使用Proxy类里面的方法创建代理对象
方法newProxyInstance(classloader loader,类《?》[] interfaces,invocationhandler h)
返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用程序
方法有三个参数,
第一个参数:类加载器
第二参数:增强方法所在的类,这个类实现的接口,支持多个接口
第三参数,实现这个接口InvocationHanderler,创建代理方法,写增强的部分

编写jdk动态代理方法

package aops;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class mm {
    public static void main(String[] args) {
        //创建解耦实现类的代理对象
        Class[] interfaces = {UserDao.class};
        Userdaoimpl u = new Userdaoimpl();
        UserDao o = (UserDao)Proxy.newProxyInstance(mm.class.getClassLoader(), interfaces, new UserDaoProcy(u));
        int add = o.add(2, 3);
        System.out.println(add);

    }
}
class UserDaoProcy implements InvocationHandler{
    private Userdaoimpl u;

    public UserDaoProcy(Userdaoimpl u) {
        this.u = u;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法之前"+method.getName()+"传递的参数。。"+ Arrays.toString(args));
        Object res = method.invoke(u, args);
        System.out.println("方法之后"+res);
        return res;
    }


}

4、AOP的术语

1、连接点

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

2、切入点

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

3、通知(增强)

实际增强的逻辑部分称为通知

通知有多种类型

前置通知
后置通知
环绕通知:方法前面后面都执行
异常通知:有异常执行
最终通知:类似finally

4、切面

动作

把通知应用到切入点过程

5、AOP操作(准备)

1、spring框架中一般基于AspectJ实现AOP操作

aspectj不是spring组成的部分,独立aop框架,一般把aspectj和spring框架一起使用,进行aop操作

2、基于aspectj实现aop操作

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

(2)基于注解方式实现

3、切入点表达式

切入点表达式的作用:知道对哪个类里面的哪一个方法进行增强

语法结构

execution(权限修饰符【类全路径】【方法名称】【参数列表】)

6、AOP操作(Aspectj注解)重点

创建类,在类里面定义方法

1、创建类,在类里面定义方法
public class User {
 public void add() {
 System.out.println("add.......");
 }
}
2、创建增强类(编写增强逻辑)
(1)在增强类里面,创建方法,让不同方法代表不同通知类型
//增强的类
public class UserProxy {
 public void before() {//前置通知
 System.out.println("before......");
 }
}
3、进行通知的配置
(1)在 spring 配置文件中,开启注解扫描
<?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: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">
 <!-- 开启注解扫描 -->
 <context:component-scan basepackage="com.atguigu.spring5.aopanno"></context:component-scan>
(2)使用注解创建 User 和 UserProxy 对象
(3)在增强类上面添加注解 @Aspect
//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
(4)在 spring 配置文件中开启生成代理对象
<!-- 开启 Aspect 生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4、配置不同类型的通知
(1)在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置
//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
 //前置通知
 //@Before 注解表示作为前置通知
 @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
 public void before() {
 System.out.println("before.........");
 }
 //后置通知(返回通知)
 @AfterReturning(value = "execution(* 
com.atguigu.spring5.aopanno.User.add(..))")
 public void afterReturning() {
 System.out.println("afterReturning.........");
 }
 //最终通知
 @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
 public void after() {
 System.out.println("after.........");
 }
 //异常通知
 @AfterThrowing(value = "execution(* 
com.atguigu.spring5.aopanno.User.add(..))")
 public void afterThrowing() {
 System.out.println("afterThrowing.........");
 }
 //环绕通知
 @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
 public void around(ProceedingJoinPoint proceedingJoinPoint) throws 
Throwable {
 System.out.println("环绕之前.........");
 //被增强的方法执行
 proceedingJoinPoint.proceed();
 System.out.println("环绕之后.........");
 }
}

5、相同的切入点抽取

//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void pointdemo() {
}
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
 System.out.println("before.........");
}

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

add前面的优先级越高越先执行,add后面优先级越高越后执行

(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高
@Component
@Aspect
@Order(1)
public class PersonProxy
7、完全使用注解开发 
(1)创建配置类,不需要创建 xml 配置文件 
@Configuration
@ComponentScan(basePackages = {"com.atguigu"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

7、AOP操作(AspectJ配置文件)

1、创建两个类,增强类和被增强类,创建方法
2、在 spring 配置文件中创建两个类对象
<!--创建对象-->
<bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>
3、在 spring 配置文件中配置切入点
<!--配置 aop 增强-->
<aop:config>
 <!--切入点-->
 <aop:pointcut id="p" expression="execution(* 
com.atguigu.spring5.aopxml.Book.buy(..))"/>
 <!--配置切面-->
 <aop:aspect ref="bookProxy">
 <!--增强作用在具体的方法上-->
 <aop:before method="before" pointcut-ref="p"/>
 </aop:aspect>
</aop:config>

四、jdbcTemplate

1、def

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

2、增加,修改,删除

1、对应数据库创建实体类
2、编写 service 和 dao
(1)在 dao 进行数据库添加操作
(2)调用 JdbcTemplate 对象里面 update 方法实现添加操作
⚫ 有两个参数
⚫ 第一个参数:sql 语句
⚫ 第二个参数:可变参数,设置 sql 语句值
@Repository
public class BookDaoImpl implements BookDao {
 //注入 JdbcTemplate
 @Autowired
 private JdbcTemplate jdbcTemplate;
 //添加的方法
 @Override
 public void add(Book book) {
 //1 创建 sql 语句
 String sql = "insert into t_book values(?,?,?)";
 //2 调用方法实现
 Object[] args = {book.getUserId(), book.getUsername(), 
book.getUstatus()};
 int update = jdbcTemplate.update(sql,args);
 System.out.println(update);
 }
}
3、测试类
@Test
public void testJdbcTemplate() {
 ApplicationContext context =
 new ClassPathXmlApplicationContext("bean1.xml");
 BookService bookService = context.getBean("bookService", 
BookService.class);
 Book book = new Book();
 book.setUserId("1");
 book.setUsername("java");
 book.setUstatus("a");
 bookService.addBook(book);
}
JdbcTemplate 操作数据库(修改和删除)
1、修改
@Override
public void updateBook(Book book) {
 String sql = "update t_book set username=?,ustatus=? where user_id=?";
 Object[] args = {book.getUsername(), book.getUstatus(),book.getUserId()};
 int update = jdbcTemplate.update(sql, args);
 System.out.println(update);
}
2、删除
@Override
public void delete(String id) {
 String sql = "delete from t_book where user_id=?";
 int update = jdbcTemplate.update(sql, id);
 System.out.println(update);
}

3、查询

查询返回某个值

1、查询表里面有多少条记录,返回是某个值
2、使用 JdbcTemplate 实现查询返回某个值代码
⚫ 有两个参数 
⚫ 第一个参数:sql 语句
⚫ 第二个参数:返回类型 Class
//查询表记录数
@Override
public int selectCount() {
 String sql = "select count(*) from t_book";
 Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
 return count;
}

查询返回对象

1、场景:查询图书详情
2、JdbcTemplate 实现查询返回对象
⚫ 有三个参数 
⚫ 第一个参数:sql 语句
⚫ 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成
数据封装
⚫ 第三个参数:sql 语句值
//查询返回对象
@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;
}

查询返回集合)

1、场景:查询图书列表分页…
2、调用 JdbcTemplate 方法实现查询返回集合
⚫ 有三个参数 
⚫ 第一个参数:sql 语句
⚫ 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成
数据封装
⚫ 第三个参数:sql 语句值
//查询返回集合
@Override
public List<Book> findAllBook() {
 String sql = "select * from t_book";
 //调用方法
 List<Book> bookList = jdbcTemplate.query(sql, new 
BeanPropertyRowMapper<Book>(Book.class));
 return bookList;
}

4、JdbcTemplate 操作数据库(批量操作)

1、批量操作:操作表里面多条记录
2、JdbcTemplate 实现批量添加操作
⚫ 有两个参数 
⚫ 第一个参数:sql 语句
⚫ 第二个参数:List 集合,添加多条记录数据
//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
 String sql = "insert into t_book values(?,?,?)";
 int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
 System.out.println(Arrays.toString(ints));
}
//批量添加测试
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","java","a"};
Object[] o2 = {"4","c++","b"};
Object[] o3 = {"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用批量添加
bookService.batchAdd(batchArgs);
3、JdbcTemplate 实现批量修改操作
//批量修改
@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));
}
//批量修改
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"java0909","a3","3"};
Object[] o2 = {"c++1010","b4","4"};
Object[] o3 = {"MySQL1111","c5","5"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用方法实现批量修改
bookService.batchUpdate(batchArgs);
4、JdbcTemplate 实现批量删除操作
//批量删除
@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));
}
//批量删除
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3"};
Object[] o2 = {"4"};
batchArgs.add(o1);
batchArgs.add(o2);
//调用方法实现批量删除
bookService.batchDelete(batchArgs);

五、事务

1、def

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

典型场景:银行转账。

2、特性(ACID)

原子性:这个不可分割,要么都成功,要么都失败

一致性:操作之前和操作之后总量不变

隔离性:多事务操作中间不会才生影响

持久性:当提交的时候,表中数据都会产生变化

3、创建事务环境

4、事务操作

事务一般添加到javaee三层结构里面Service(业务逻辑层)

在spring进行事务管理操作

有两种方式:编程式事务管理和声明式事务管理(使用)

声明式事务管理:基于注解的方式(使用),基于xml配置文件方式

5、在spring进行声明式事务管理,底层使用AOP

6、Spring事务管理API

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

platformtransactionmanager

7、注解方式,事务操作

在spring配置文件中配置文件配置事务管理器

<!--创建事务管理器-->
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--注入数据源-->
 <property name="dataSource" ref="dataSource"></property>
</bean>

2、在 spring 配置文件,开启事务注解

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

(2)开启事务注解

<!--开启事务注解-->
<tx:annotation-driven transactionmanager="transactionManager"></tx:annotation-driven>

3、在 service 类上面(或者 service 类里面方法上面)添加事务注解 (1)@Transactional,这个注解添加到类上面,也可以添加方法上面 (2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务 (3)如果把这个注解添加方法上面,为这个方法添加事务

@Service
@Transactional
public class UserService {

8、参数配置-声明式事务管理参数配置-事务操作

propagation:事务传播行为

前两个理解:

ioslation:事务隔离级别

事务里面有特性称为隔离性,所十五操作之间不会产生影响。不考虑隔离性产生很多问题。

有三个读问题:脏读,不可重复读,幻读

脏读:一个事务没有提交另一个事务就能知道你这个做了什么。一个未提交事务读取到了另一个未提交事务的数据。

不可重复读:事务a和事务b都对一条数据进行操作,a获得工资5000,b修改工资到500,提交事务。但a能读到b提交的数据。

a没有提交的事务,读到另一个已经提交修改的数据的事务。

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

解决:事务的隔离级别

设置隔离级别:

@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)

timeout:超过时间

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

默认值是-1,,这只时间是以秒进行计算。

readOnly:是否已读

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

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

设置readonly是true,设置成true后,只能查询

rollbackFor:回滚

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

noRollbackFor:不会滚

设置出现哪些异常不进行回滚

9、事务操作(xml声明)

配置事务管理器

配置通知

配置切入点和切面

<!--1 创建事务管理器-->
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--注入数据源-->
 <property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 配置通知-->
<tx:advice id="txadvice">
 <!--配置事务参数-->
 <tx:attributes>
 <!--指定哪种规则的方法上面添加事务-->
 <tx:method name="accountMoney" propagation="REQUIRED"/>
 <!--<tx:method name="account*"/>-->
 </tx:attributes>
</tx:advice>
<!--3 配置切入点和切面-->
<aop:config>
 <!--配置切入点-->
 <aop:pointcut id="pt" expression="execution(* 
com.atguigu.spring5.service.UserService.*(..))"/>
 <!--配置切面-->
 <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>

10、事务操作(完全注解开发)

1、创建配置类,使用配置类代替xml

2、

@Configuration//配置类
@ComponentScan(basePackages = "com")//组件扫描
@EnableTransactionManagement//开启事务
public class TxConfig {
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///test");
        dataSource.setUsername("root");
        dataSource.setPassword("abc123");
        return dataSource;
    }
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager =new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}

六、spring5的新功能

整个spring5的框架的代码基于java8,运行时兼容jdk9,许多不建议使用的类和方法在代码库中删除。

spring5矿建自带了童工的日志封装

(1)spring5已经移除了Log4jConfigListener,官方建议使用Log4j2

spring5框架整合Log4j2

3、spring框架核心容器支持@Nullable注解

1、@Nullable注解可以使用在方法上面,属性上,参数上面,表示方法返回可以为空,属性值可以为空,参数值可以为空。

2、注解可以用在方法上面代表参数的返回值可以为空

3、注解可以用在方法参数里面,方法参数可以为空。

4、注解使用在属性上面,属性值可以为空

4、支持函数式风格GenericApplucationConttext

//函数式风格创建对象,交给 spring 进行管理
@Test
public void testGenericApplicationContext() {
 //1 创建 GenericApplicationContext 对象
 GenericApplicationContext context = new GenericApplicationContext();
 //2 调用 context 的方法对象注册
 context.refresh();
 context.registerBean("user1",User.class,() -> new User());
 //3 获取在 spring 注册的对象
 // User user = (User)context.getBean("com.atguigu.spring5.test.User");
 User user = (User)context.getBean("user1");
 System.out.println(user);
}

5、Spring5支持整合JUnit5

1、整合Junit4

引入spring相关测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:bean.xml")
public class JTest4 {
    @Autowired
    private UserService userService;
    @Test
    public void test(){
        userService.accountMoney();
    }
}

2、整合JUNIt5

//@ExtendWith(SpringExtension.class)//
//@ContextConfiguration("classpath:bean.xml")
@SpringJUnitConfig(locations = "classpath:bean.xml")
public class JUnit5 {
    @Autowired
    private UserService userService;
    @Test
    public void test(){
        userService.accountMoney();
    }
}

七、WebFlux,spring新框架

前置信息,springmvc,springboot,maven,java8新特性

1、springWebFlux介绍

2、响应式编程

3、WebFlux执行流程和核心API

4、SoringWebFlux(基于注解编程模型)

5、SpringWebFlux(基于函数式编程模型)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值