Spring5框架学习笔记(上)

在此记录我初学spring的笔记,方便以后用到时查看,也分享出来给大家一起学习。参考视频教程:Spring5

从第四部分开始在:Spring5框架学习笔记(下)

笔记中所涉及到的project(用的是idea):spring5学习代码,提取码flad

Spring5学习笔记

  • 一、框架概述
    • 入门案例
  • 二、IOC容器
    • 1、IOC概念原理
    • 2、IOC接口
    • 3、IOC操作 Bean管理
        • (1)什么是Bean管理?指的是两个操作:
        • (2)Bean管理操作的几种方式
        • (3)xml注入其他类型属性
        • (4)注入集合类型的属性
        • (5)在集合里设置对象类型值
        • (6)把集合注入部分提取出来
    • 4、IOC操作 Bean管理---FactoryBean
    • 5、IOC操作 Bean管理---bean的作用域
    • 6、IOC操作Bean管理---bean生命周期
    • 7、IOC操作Bean管理---xml自动装配
    • 8、IOC操作Bean管理---外部属性文件
    • 9、IOC操作Bean管理---基于注解方式
  • 三、AOP
    • 1、概念
    • 2、AOP---JDK动态代理
      • (1)==编写JDK动态代理方法==
      • (2)AOP术语
      • (3)AOP操作(准备)
      • (4)AOP操作(AspectJ注解)
      • (5)AOP操作(AspectJ配置文件)(较少用)
  • 四、JDBCTemplate

一、框架概述

  • Spring是轻量级的开源的JavaEE框架,可以解决企业应用开发的复杂性
  • Spring有两个核心部分:IOC和AOP
    (1)IOC:控制反转,把创建对象的过程(new)交给Spring进行管理
    (2)AOP:面向切面,在不修改源代码的情况下进行功能的增强

Spring框架的特点:

(1)方便解耦,简化开发
(2)AOP编程支持
(3)方便程序的测试
(4)可以方便和其他框架进行整合
(5)方便进行实事务操作
(6)降低API开发难度

spring下载地址

入门案例

1、新建java工程(maven也可以)
2、在工程下新建一个lib文件,其中加入所需要的的jar包(其中后面4个包是在前面下载的spring文件夹中可以找到的,第一个需要另外去下载,下载地址)
Spring5框架学习笔记(上)_第1张图片
Spring5框架学习笔记(上)_第2张图片
3、点Files—>project Structure,找到module,添加这几个jar包(点+后选择第一个,JARs or directions)
Spring5框架学习笔记(上)_第3张图片
4、创建一个普通类,在这个类创建普通方法

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

5、创建Spring配置文件,在这个类创建普通方法
(1)Spring配置文件使用xml格式
新建一个bean1.xml(名字随意)文件,选择Spring config,下面是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">

       <!-- 配置User对象创建,id是名字,class里面是路径-->
    <bean id="user" class="spring5.User"></bean>
</beans>

6、测试代码编写
(这里用了junit单元测试,需要一定的基础)

package spring5.testDemo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring5.User;

public class TestSpring5 {

    @Test
    public void testAdd(){
        //1.加载spring的配置文件
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean1.xml");
        //2.获取配置创建的对象
        User user=context.getBean("user", User.class);

        System.out.println(user);
        user.add();
    }
}

二、IOC容器

1、IOC概念原理

(1)什么是IOC?

  • 控制反转,把对象创建和对象之间的调用过程,交给Spring管理
  • 使用IOC目的:使耦合度降低
  • 上文的入门案例就是IOC实现

(2)IOC底层原理:xml解析、工厂模式、反射
Spring5框架学习笔记(上)_第4张图片
Spring5框架学习笔记(上)_第5张图片
(3)IOC过程
①配置xml文件,配置创建的对象

<bean id="dao" class="xxx.UserDao"></bean> //xxx是包的名称,具体根据路径来

②有service类和dao类,创建工厂类

class UserFactory{
    public static UserDao getDao(){
        String classValue=class属性值;//1.xml解析得到
        Class clazz= Class.forName(classValue)//2.通过反射创建对象
        return (UserDao)clazz.newInstance()
    }
}

2、IOC接口

(1)IOC思想基于IOC容器完成,IOC容器本质上就是对象工厂
(2)Spring提供两种IOC容器实现方式:

BeanFactory:最基本的实现方式,是Spring内部的使用接口,不提供开发人员进行使用。
*加载配置文件的时候不会创建对象,在获取对象(使用)时才创建对象。

ApplicationContext:BeanFactory接口的子接口,提供了更多更强大的功能,一般由开发人员进行使用
*加载配置文件的时候就会创建对象

(3)ApplicationContext接口的实现类
Spring5框架学习笔记(上)_第6张图片
(红框中是两个主要的)

3、IOC操作 Bean管理

(1)什么是Bean管理?指的是两个操作:

  • Spring创建对象
  • Spring注入属性

(2)Bean管理操作的几种方式

①基于xml配置文件方式实现:
a. 在Spring配置文件中使用bean标签,标签里面添加对应属性,即可实现对象创建
在这里插入图片描述
b. 介绍bean标签中常用的属性:
*id属性:唯一标识(不能有特殊符号)
*class属性:类的全路径(包类路径)

c. 创建对象的时候,默认是执行无参数构造方法(如果只有有参构造函数会报错)

②基于注解方式实现
a. DI:依赖注入,即注入属性
第一种注入方式:使用set方法:创建类,定义对应的属性和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;
    }
   public void testDemo(){
        System.out.println(bName+"::"+bAuthor);
    }
}

//xml配置部分
<bean id="book" class="spring5.Book">
        <!-- 使用property完成属性注入
        name:类中的属性名称
        value:向属性注入的值
        -->
        <property name="bName" value="算法"></property>
        <property name="bAuthor" value="张三"></property>
    </bean>`

//测试部分
@Test
    public void testBook1(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean1.xml");

        Book book=context.getBean("book",Book.class);

        System.out.println(book);
        book.testDemo();

    }

有参构造

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

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

//xml配置
 <bean id="orders" class="spring5.Orders">
        <constructor-arg name="name" value="abc"></constructor-arg>
        <constructor-arg name="address" value="china"></constructor-arg>
</bean>

③p名称空间注入(了解)
在这里插入图片描述
在这里插入图片描述

(3)xml注入其他类型属性

①字面量

//null值
<property name="address">
    <null/>
</property>
<!-- 属性值包含特殊符号-->
        <property name="address">
            <value><![CDATA[<<南京>>]]></value>
        </property>

②注入属性—外部bean

a. 创建两个类service和dao
b. 在service类中调用dao里面的方法
c. 在Spring配置文件中配置
Spring5框架学习笔记(上)_第7张图片

userdao接口

package spring5.dao;

public interface UserDao {
    public void update();
}

接口实现

package spring5.dao;

public class UserDaoImpl implements UserDao{

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

service

package spring5.service;

import spring5.dao.UserDao;

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

xml配置

<!--    service和dao对象创建-->
    <bean id="userService" class="spring5.service.UserService">
    <!-- 注入userDao对象
        name值:类里面属性名称
        ref:创建userDao对象那个bean标签的id值(对应之前的value)
     -->
        <property name="userDao"  ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="spring5.dao.UserDaoImpl"></bean>
</beans>

测试

public class TestBean {
    @Test
    public void test(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean2.xml");

        UserService userService=context.getBean("userService",UserService.class);
        userService.add();
    }
}

输出:
在这里插入图片描述

③注入属性—内部bean

  • 一对多关系:部门(一)和员工(多)
  • 在实体类之间表示一对多的关系,员工的所属部门使用对象类型来表示
  • 在Spring配置文件中进行配置

Dept类

package spring5.bean;

public class Dept {
    private String dname;
    public void setDname(String dname){
        this.dname=dname;
    }
}
@Override
public String toString() {
    return "Dept{" +
            "dname='" + dname + '\'' +
            '}';
}//为了测试用的

Emp类

package spring5.bean;

public class Emp {
    private String ename;
    private String gender;
    //员工属于某一个部门
    private Dept dept;
    public void setEname(String ename) {
        this.ename = ename;
    }

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

    public void setDept(Dept dept) {
        this.dept = dept;
    }
    public void add(){
        System.out.println(ename+":"+gender+":"+dept);
    }
}

xml配置

<bean id="emp" class="spring5.bean.Emp">
        <!--  设置两个普通属性-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value="female"></property>
        <!-- 内部bean-->
        <property name="dept">
            <bean id="dept" class="spring5.bean.Dept">
                <property name="dname" value="安保"></property>
            </bean>
        </property>
    </bean>

④注入属性—级联赋值

<bean id="emp" class="spring5.bean.Emp">
    <property name="ename" value="lucy"></property>
    <property name="gender" value="female"></property>
    <!-- 级联赋值-->
    <property name="dept" ref="dept"></property>
</bean>
<bean id="dept" class="spring5.bean.Dept">
    <property name="dname" value="caiwu"></property>
</bean>

(4)注入集合类型的属性

代码见spring5_demo2/collectiontype/Stu和spring5_demo2/bean1文件

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

    <!-- 集合类型属性注入-->
    <bean id="stu" class="spring5.Stu">
        <!-- 数组类型属性-->
        <property name="courses">
            <array>
                <value>java课程</value>
                <value>数据库课程</value>
            </array>
        </property>
        <!-- list类型属性-->
        <property name="list">
            <list>
                <value>zhangsan</value>
                <value>xiaosan</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>

</beans>

(5)在集合里设置对象类型值

<!-- 注入list类型属性,值是对象-->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
<!--创建多个course对象-->
    <bean id="course1" class="spring5.collectiontype.Course">
        <property name="cname" value="Spring5框架课程"></property>
    </bean>
    <bean id="course2" class="spring5.collectiontype.Course">
        <property name="cname" value="MyBatis课程"></property>
    </bean>

详细见代码

(6)把集合注入部分提取出来

①在Spring配置文件中引入名称空间util
②使用util标签完成list集合注入提取

代码见spring5_demo2/collectiontype/Book和spring5_demo2/bean2文件
Spring5框架学习笔记(上)_第8张图片

<?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/beans/spring-util.xsd">

    <!-- 1 提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>易筋经</value>
        <value>九阴真经</value>
        <value>九阳神功</value>
    </util:list>
    <!-- 2 提取list集合类型属性注入使用-->
    <bean id="book" class="spring5.collectiontype.Book">
        <property name="list" ref="bookList"></property>
    </bean>
</beans>

4、IOC操作 Bean管理—FactoryBean

1、Spring有两种类型bean,一种普通bean,另一种工厂bean(FactoryBean)

  • 普通bean:在配置文件中定义的bean类型就是返回类型
  • 工厂bean:在配置文件中定义的bean类型可以和返回类型不一样

2、工厂bean
(1)创建类,让这个类作为工厂bean,实现接口FactoryBean
(2)实现接口里面的方法,在实现的方法中定义返回的bean类型

(代码见bean3和factorybean)

package spring5.factorybean;

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

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;
    }
}
@Test
    public void test3(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean3.xml");
        Course myBean=context.getBean("myBean", Course.class);
        System.out.println(myBean);
    }

5、IOC操作 Bean管理—bean的作用域

1、在Spring里面,设置创建bean实例是单实例还是多实例
2、在Spring里,默认情况下,bean是单实例对象

@Test
    public void testCollection2(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book1=context.getBean("book", Book.class);
        Book book2=context.getBean("book", Book.class);
        System.out.println(book1);
        System.out.println(book2);
    }

输出:两个book地址相同,说明是单实例对象
在这里插入图片描述
如何设置单实例还是多实例

bean标签里面有属性scope可用于设置
①默认值,singleton,表示单实例对象
②prototype,表示是多实例对象
③scope设置为singleton时,加载spring配置文件的时候就会创建单实例对象;设置为prototype时,不是加载spring配置文件时创建对象,是在调用getBean方法时创建的多实例对象

<bean id="book" class="spring5.collectiontype.Book" scope="prototype">
        <property name="list" ref="bookList"></property>
</bean>

在这里插入图片描述

6、IOC操作Bean管理—bean生命周期

(1)生命周期:从对象创建到对象销毁的过程

(2)bean生命周期:

  • 通过构造器创建bean实例(无参数构造)
  • 为bean的属性设置值和对其他bean引用(调用set方法)
  • 调用bean的初始化的方法(需要进行配置)
  • bean可以使用了(对象获取到了)
  • 当容器关闭时,调用bean的销毁方法(需要进行配置)

(3)演示
(代码见bean4和bean/Orders和testBean3函数)

package 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方法设置值");
    }
    //创建执行的初始化的方法
    public void initMethod(){
        System.out.println("第三步 执行初始化的方法");
    }
    //创建执行销毁的方法
    public void destroyMethod(){
        System.out.println("第五步 执行销毁的方法");
    }
}
<?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="spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>
</beans>

Spring5框架学习笔记(上)_第9张图片
(4)bean的后置处理器,bean生命周期有七步

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

(5)演示(添加后置处理器)
(代码见spring5/bean/MyBeanPost)

①创建类,实现接口BeanPostProcessor

package spring5.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之前执行的");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之后执行的");
        return bean;
    }
}

②xml文件
在这里插入图片描述
这句会为当前文件中所有bean创建后置处理器(MyBeanPost实现了那个接口所以会识别)

③执行testBean3函数
Spring5框架学习笔记(上)_第10张图片

7、IOC操作Bean管理—xml自动装配

自动装配:根据指定装配规则(属性名称或属性类型),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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--实现自动装配
    bean标签属性autowire,配置自动装配
    autowire属性常用两个值:
        byName根据属性名称注入,注入值的bean id与类的属性名称一样
        byType根据属性类型注入
    -->
    <bean id="emp" class="spring5.autowire.Emp" autowire="byName">

    </bean>
    <bean id="dept" class="spring5.autowire.Dept"></bean>
</beans>

8、IOC操作Bean管理—外部属性文件

1、直接配置数据库信息
(1)配置德鲁伊连接池
(2)引入德鲁伊连接池依赖jar包

<!--直接配置连接池-->
    <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、引入外部属性文件配置数据库连接池

(1)创建外部属性文件,properties文件,写数据库信息

jdbc.properties

//prop这个名字是随意取的
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=root

(2)把外部properties属性文件引入Spring配置文件中

**引入context名称空间
Spring5框架学习笔记(上)_第11张图片
xml文件代码(见demo2的bean6)

<?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">
    
    <!-- 引入外部属性文件-->
    <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>

9、IOC操作Bean管理—基于注解方式

(前面的都是基于xml方式)
代码在demo3工程

1、什么是注解

  • 注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)
  • 注解可作用在类,方法,属性上
  • 使用注解目的:简化xml配置

2、Spring针对Bean管理中创建对象提供注解

  • @Component
  • @Service
  • @Controller
  • @Repository

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

3、基于注解实现对象创建

①引入依赖
在这里插入图片描述
②引入context命名空间,开启组件扫描
③创建类,在类上面添加创建对象注解

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

    <!-- 开启组件扫描
    1、扫描多个包,使用逗号隔开
    2、扫描多个包也可以扫描包的上层目录
    -->
    <context:component-scan base-package="spring5"></context:component-scan>
</beans>

组件扫描的其他细节设置

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

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

  • @AutoWired:根据属性类型进行自动装配

第一步:把service和dao对象创建,在service和dao类添加创建对象注解
第二步:在service注入dao对象,在service类中添加dao类型的属性,在属性上面使用注解

package spring5.service;

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

//注解里面value属性值可以省略,默认值是类名称,首字母小写
@Component(value="userService")   //
public class UserService {
    //定义dao类型属性(不需要添加set方法)
    @Autowired  //根据类型进行注入
    private UserDao userDao;
    public void add(){
        System.out.println("service add...");
        userDao.add();
    }
}

(测试用testService函数)

@Test
    public void testService(){
        ApplicationContext context
                =new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService=context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }
  • @Qualifier:根据属性名称注入(和上面的AutoWired一起使用)
package spring5.dao;

import org.springframework.stereotype.Repository;

@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao{
    @Override
    public void add() {
        System.out.println("dao add...");
    }
}
@Component(value="userService")   //
public class UserService {
    //定义dao类型属性(不需要添加set方法)
    @Autowired  //根据类型进行注入
    @Qualifier(value = "userDaoImpl1")
    private UserDao userDao;
    public void add(){
        System.out.println("service add...");
        userDao.add();
    }
}
  • @Resource:可以根据类型或名称注入
@Resource(name="userDaoImpl1")
    private UserDao userDao;

@Resource
    private UserDao userDao;
  • @Value:注入普通类型属性
@Component(value="userService")   //
public class UserService {
    @Value(value="abc")
    private String name;

    public void add(){
        System.out.println("service add..."+name);
        userDao.add();
    }
}

5、完全注解开发

  • 创建配置类,替代xml文件
@Configuration //作为配置类,替代xml文件
@ComponentScan(basePackages = {"spring5"})
public class SpringConfig {
}
  • 编写测试类
@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可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率
  • 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
    Spring5框架学习笔记(上)_第12张图片
  • 底层原理:AOP底层使用动态代理,有两种情况

(1)有接口的情况,使用JDK动态代理(创建接口实现类代理对象,增强类的方法)
Spring5框架学习笔记(上)_第13张图片
(2)没有接口情况,使用CGLIB动态代理(创建子类的代理对象,增强类的方法)Spring5框架学习笔记(上)_第14张图片

2、AOP—JDK动态代理

JDK动态代理:使用Proxy类里面的方法创建代理对象:java.lang.reflect.Proxy
调用newProxyInstance方法
在这里插入图片描述
参数一:类加载器;
参数二:增强方法所在的类实现的接口,支持多个接口
参数三:实现接口InvoationHandler,创建代理对象,写增强的方法

(1)编写JDK动态代理方法

(代码见demo4)

(1)创建接口,定义方法
public interface UserDao {
    public int add(int a,int b);
    public String update(String id);
}2)创建接口实现类,实现方法
package spring5;

public class UserDaoImpl implements UserDao{
    @Override
    public int add(int a, int b) {
        System.out.println("add执行了");
        return a+b;
    }

    @Override
    public String update(String id) {
        System.out.println("update执行了");
        return id;
    }
}3)使用Proxy类创建接口代理对象
 package spring5;

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

public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces={UserDao.class};

        UserDaoImpl userDao=new UserDaoImpl();
        UserDao dao=(UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces,new UserDaoProxy(userDao));
        int res=dao.add(1,2);
        System.out.println("result:"+res);
    }

}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler{
    /**1、传递被代理对象到代理类中
     UserDaoImpl中的add方法要被增强,所以要把UserDaoImpl的对象传递过去(就是这里的obj)
     用有参构造传递
     */
    private Object obj;
    public UserDaoProxy(Object obj){
        this.obj=obj;
    }
     //这里写增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("方法之前执行了"+method.getName()+" :传递的参数"+ Arrays.toString(args));
        //被增强的方法(obj就是创建的代理对象)
        Object res=method.invoke(obj,args);
        //方法之后
        System.out.println("方法之后执行"+obj);

        return res;
    }
}

(2)AOP术语

①连接点:类里面可以被增强的方法

②切入点:实际被真正增强的方法
③通知(增强):实际增强的逻辑部分

前置通知(增强的方法之前执行)
后置通知
环绕通知
异常通知(方法出现异常会执行)
最终通知(finally)

④ 切面:把通知应用到切入点的过程(是一个动作)

(3)AOP操作(准备)

①Spring框架一般都是就AspectJ实现AOP操作

AspectJ不是Spring组成部分,是独立AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作

②基于AspectJ实现AOP操作

基于xml配置文件实现
基于注解方式(使用)

③在项目中引入AOP相关依赖
Spring5框架学习笔记(上)_第15张图片
④切入点表达式

a. 切入点表达式作用:知道对哪个类里面的哪个方法进行增强
b. 语法结构: execution([权限修饰符][返回类型][类的全路径][方法名称]([参数列表]))

*举例1:对spring5.dao.BookDao类里面的add进行增强

execution(*spring5.dao.BookDao.add(..))//*表示所有的权限修饰符
*举例2:对spring5.dao.BookDao类里面所有的方法进行增强
execution(*spring5.dao.BookDao.*(..))
*举例3:对spring5.dao包里面所有类的所有方法进行增强
execution(*spring5.dao.*.*(..))

(4)AOP操作(AspectJ注解)

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

//被增强的类
public class User {
    public void add() {
        System.out.println("User add()....");
    }
}

②创建增强类(编写增强的逻辑)。在增强类里面创建方法,让不同方法代表不同通知类型

/**
 * @Description:增强的类
 */
public class UserProxy {
    public void before(){
        System.out.println("before....");
    }
}

③进行通知的配置

a. 在Spring的配置文件中,开启注解扫描

b. 使用注解创建User和UserProxy对象
Spring5框架学习笔记(上)_第16张图片
Spring5框架学习笔记(上)_第17张图片
c. 在增强类上添加注解@Aspect

d. 在spring配置文件中开启生成代理对象

<!-- 开启 AspectJ 生成注解对象
       扫描有 @Aspect 注解的类, 有这个注解的就生成代理对象
       -->
 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

④配置不同类型的通知

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

@Component
@Aspect //生成代理对象
public class UserProxy {
    //    相同切入点抽取
    @Pointcut(value = "execution(* spring5.aopanno.User.add(..))")
    public void pointdemo() {

    }

    //前置通知,@Before注解表示为前置通知
    @Before(value = "execution(* spring5.aopanno.User.add(..))")
    public void before(){
        System.out.println("before....");
    }

    //    返回结果之后执行
    @AfterReturning(value = "pointdemo()")
    public void afterReturning() {
        System.out.println("afterReturning....");
    }

    //   方法之后执行,最终通知,不管有无异常都执行
    @After(value = "pointdemo()")
    public void after() {
        System.out.println("after....");
    }

    //  异常通知
    @AfterThrowing(value = "pointdemo()")
    public void afterThrowing() {
        System.out.println("afterThrowing....");
    }

    //    环绕通知
    @Around(value = "pointdemo()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前....");

        //被增强的方法执行
        proceedingJoinPoint.proceed();

        System.out.println("环绕之后....");
    }
}

Spring5框架学习笔记(上)_第18张图片
⑤相同切入点抽取

 //    相同切入点抽取
    @Pointcut(value = "execution(* spring5.aopanno.User.add(..))")
    public void pointdemo() {

    }

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

(假设有另一个类PersonProxy也对add方法做增强)

在增强类上添加注解@Order(数字),数字值越小优先级越高
Spring5框架学习笔记(上)_第19张图片
⑦完全使用注解开发
创建配置类,不需要配置xml文件

@Configuration
@ComponentScan(basePackages = {"spring5"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
// 替代配置文件中的 
public class ConfigAop {
}

(5)AOP操作(AspectJ配置文件)(较少用)

①创建两个类,增强类和被增强类,创建方法

public class Book {
    public void buy(){
        System.out.println("buy...");
    }
}
public class BookProxy {
    public void before(){
        System.out.println("before...");
    }
}

②在spring配置文件中创建两个类对象
③在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: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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    创建对象-->
    <bean id="book" class="spring5.aopxml.Book"></bean>
    <bean id="bookProxy" class="spring5.aopxml.BookProxy"></bean>

<!--    配置aop增强-->
    <aop:config>
        <!-- 切入点,id随便取名-->
        <aop:pointcut id="p" expression="execution(* spring5.aopxml.Book.buy(..))"/>

        <!--配置切面,ref是增强类-->
        <aop:aspect ref="bookProxy">
            <!-- 配置增强作用在具体方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>

    </aop:config>
</beans>

四、JDBCTemplate

你可能感兴趣的:(计算机,spring)