Spring

文章详细介绍了Spring框架的核心概念,包括控制反转(IOC)的思想、对象容器、对象创建策略、生命周期方法以及依赖注入(DI)。同时,讨论了Spring如何通过XML和注解实现IOC,以及DI的不同方式。此外,提到了Spring与MyBatis的整合,包括环境搭建和配置文件编写。
摘要由CSDN通过智能技术生成

Spring

Spring 简介

Spring是一个开源框架,为简化企业级开发而生.它以IOC(控制反转)和AOP(面向切片)为思想核心,提供了控制层SpringMVC,数据层SpringData,服务层事务管理等众多技术,并可以整合众多的第三方框架.Spring将很多复杂的代码变得优雅简洁,有效的降低代码的耦合
度,极大的方便项目的后期维护、升级和扩展。
Spring官网

Spring 体系结构

Spring框架根据不同的功能被划分成了多个模块,这些模块可以满足一切企业级应用开发的需求,在开发过程中可以根据需求有选择
性地使用所需要的模块。
1.Core ContainerSpring核心模块,任何功能的使用都离不开该模块,是其他模块建立的基础。
2. Data Access/Integration:该模块提供了数据持久化的相应功能。
3.Web:该模块提供了web开发的相应功能。
4. AOP:提供了面向切面编程实现
5. Aspects:提供与AspectJ框架的集成,该框架是一个面向切面编程框架。
6. Instrumentation:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使用.
7. Messaging:为Spring框架集成一些基础的报文传送应用;
8. Test:提供与测试框架的集成

IOC_控制反转思想

IOC(Inversion of Control) :程序将创建对象的权利交给框架。之前在开发过程中,对象实例的创建是由调用者管理的.以前new 对象写法有两个缺点:

  • 浪费资源:StudentService调用方法时即会创建一个对象,如果不断调用方法则会创建大量StudentDao对象。
  • 代码耦合度高:假设随着开发,我们创建了StudentDao另一个更加完善的实现类StudentDaoImpl2,如果在StudentService中想使用StudentDaoImpl2,则必须修改源码

而IOC思想是将创建对象的权利交给框架,框架会帮助我们创建对象,分配对象的使用,控制权由程序代码转移到了框架中,控制权发生了反转,这就是Spring的IOC思想。而IOC思想可以完美的解决以上两个问题

IOC_自定义对象容器 (类似于我们自定义的工程)

创建一个静态的map集合容器,通过读取配置文件,反射先将对象创建出来放到容器中,需要使用对象时,只需要从容器中获取对象即可,而不需要重新创建,此时容器就是对象的管理者。

IOC_Spring实现IOC

IOC容器

1,创建Maven工程,POM.XML 引入依赖
<!--加入spring的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.27</version>
    </dependency>
2,创建Service类、Dao类和接口
UserDao接口
public interface UserDao {
    public void selectByUserName();
    public void insert();
}
Dao实现类
public class UserDaoImpl implements UserDao {
    @Override
    public void selectByUserName() {
        System.out.println("根据用户名查询一个用户!");
    }
    @Override
    public void insert() {
        System.out.println("保存一个用户!");
    }
}
UserService接口
public interface UserService {
    public void register();
}
实现类
public class UserServiceImpl implements UserService {
    private UserDao userDao;

        public UserServiceImpl() {
        }

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void register() {
        userDao.selectByUserName();
        userDao.insert();
    }

    public void setUserDao(UserDaoImpl userDao) {
        this.userDao = userDao;
    }
}
3,编写xml配置文件,配置文件中配置需要Spring帮我们创建的对象。在resource下创建applicationContext.xml文件
   <bean id="userDao" class="dao.impl.UserDaoImpl"></bean>
    <bean id="userService" class="service.impl.UserServiceImpl">
    	// 为service中的dao对象进行赋值,从容器拿到对应的bean对象,简称依赖注入 ref=bean对象
        <property name="userDao" ref="userDao"/>
    </bean>
4,测试从Spring容器中获取对象。
public class UserSericeTest {
    public static void main(String[] args) {
        // 创建容器,可以写多个配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) ac.getBean("userService");
        service.register();
    }
}
5,测试结果

测试

IOC_Spring容器类型

容器接口
  • BeanFactory:BeanFactory是Spring容器中的顶层接口,它可以对Bean对象进行管理。
  • ApplicationContext:ApplicationContext是BeanFactory的子接口。它除了继承 BeanFactory的所有功能外,还添加了对国际化、资源访问、事件传播等方面的良好支持。ApplicationContext有以下三个常用实现类:
容器的实现类
  • ClassPathXmlApplicationContext:该类可以从项目中读取配置文件
  • ApplicationContext ac = new ClassPathXmlApplicationContext(“bean.xml”);

  • FileSystemXmlApplicationContext:该类从磁盘中读取配置文件
  • FileSystemXmlApplicationContext(“C:\Users\a\IdeaProjects\spring_demo\src\main\resources\bean.xml”);

  • AnnotationConfigApplicationContext:使用该类不读取配置文件,而是会读取注解
  • AnnotationConfigApplicationContext(SpringConfig.class) // 通过注解创建的配置文件.java

IOC_对象的创建方式

Spring会帮助我们创建bean,使用构造方法,Spring默认使用类的空参构造方法创建bean
使用工厂类的方法Spring可以调用工厂类的方法创建bean:
  • 创建工厂类,工厂类提供创建对象的方法:
public class StudentDaoFactory {
    public StudentDao getStudentDao(){
        return new StudentDaoImpl(1);
   }
}
  • 在配置文件中配置创建bean的方式为工厂方式。
<!-- id:工厂对象的id,class:工厂类 -->
<bean id="studentDaoFactory" class="dao.StudentDaoFactory"></bean>
<!-- id:bean对象的id,factory-bean:工厂对象的id,factory-method:工厂方法 -->
<bean id="studentDao" factory-bean="studentDaoFactory" factory-method="getStudentDao"></bean>
使用工厂类的静态方法
public class StudentDaoFactory2 {
    public static StudentDao getStudentDao2() {
        return new StudentDaoImpl();
   }
}

xml 
<!-- id:bean的id class:工厂全类名 factorymethod:工厂静态方法   -->
<bean id="studentDao" class="dao.StudentDaoFactory2" factory-method="getStudentDao2"></bean>

IOC_对象的创建策略

Spring通过配置<bean>中的 scope 属性设置对象的创建策略,共有五种创建策略:

  • singleton:单例,默认策略。整个项目只会创建一个对象,通过 <bean> 中的 lazy-init 属性可以设置单例对象的创建时机:
  • lazy-init=“false”(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。
    lazy-init=“true”:延迟创建,第一次使用Bean对象时才会创建。

  • <!-- <bean id="studentDao" class="dao.StudentDaoImpl2" scope="singleton" lazy-init="true"> </bean>-->
  • prototype:多例,每次从容器中获取时都会创建对象。
  • request:每次请求创建一个对象,只在web环境有效。
  • session:每次会话创建一个对象,只在web环境有效。
  • gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。

IOC_对象的销毁时机

  • singleton:对象随着容器的销毁而销毁。
  • prototype:使用JAVA垃圾回收机制销毁对象。
  • request:当处理请求结束,bean实例将被销毁。
  • session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
  • gloabal-session:集群环境下的session销毁,bean实例也将被销毁。

IOC_生命周期方法

Bean对象的生命周期包含创建——使用——销毁,Spring可以配置Bean对象在创建和销毁时自动执行的方法,
对象执行的顺序
代码块>构造方法 >依赖注入> init方法

定义生命周期方法
public class StudentDaoImpl2 implements
StudentDao{
     // 创建时自动执行的方法
    public void init(){
        System.out.println("创建StudentDao!!!");
   }
    // 销毁时自动执行的方法
    public void destory(){
        System.out.println("销毁StudentDao!!!");
   }
}
----------------------------------------------------
配置生命周期方法
<!-- init-method:创建对象时执行的方法 
destroy-method:销毁对象时执行的方法 -->
<bean id="studentDao" class="dao.StudentDaoImpl2"
scope="singleton" init-method="init" destroymethod="destory"></bean>

IOC_获取Bean对象的方式

  • 通过id/name获取 StudentDao studentDao = (StudentDao) ac.getBean("studentDao");
  • 通过类型获取StudentDao studentDao2 = ac.getBean(StudentDao.class);
  • 通过类型+id/name获取虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用类型+id/name获取 StudentDao studentDao2 =ac.getBean("studentDao",StudentDao.class);

DI_什么是依赖注入

依赖注入(Dependency Injection,简称DI),它是Spring控制反转思想的具体实现。
控制反转将对象的创建交给了Spring,但是对象中可能会依赖其他对象。比如service类中要有dao类的属性,我们称service依赖于dao。之前需要手动注入属性值,此时,当StudentService的想要使用StudentDao的另一个实现类如StudentDaoImpl2时,则需要修改Java源码,造成代码的可维护性降低,而使用Spring框架后,Spring管理Service对象与Dao对象,此时它能够为Service对象注入依赖的Dao属性值。这就是Spring的依赖注入。简单来说,控制反转是创建对象,依赖注入是为对象的属性赋值

DI_依赖注入方式

Spring可以通过调用setter方法或构造方法设置对象属性值

Setter注入
  • 被注入类
public class StudentService {
    private StudentDao studentDao;
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
   }
}
  • 配置文件中,给需要注入属性值的 中设置
<bean id="studentDao" class="dao.StudentDaoImpl"></bean>
<bean id="studentService" class="service.StudentService">
    <!--依赖注入-->
    <!--name:对象的属性名 ref:容器中对象的id值-->
    <property name="studentDao" ref="studentDao"></property>
</bean>
构造方法注入
  • 被注入类编写有参的构造方法,注:记得加上无参构造方法,否则在后面做其他测试时,创建bean对象的时候会报错
public class StudentService {
    private StudentDao studentDao;
    public StudentService(StudentDao studentDao) {
        this.studentDao = studentDao;
   }
}
  • 给需要注入属性值的 <bean> 中设置 <constructor-arg>,即有参构造
<bean id="studentDao" class="dao.StudentDaoImpl"></bean>
<bean id="studentService" class="=service.StudentService">
    <!-- 依赖注入 -->
    <!-- name:对象的属性名 ref:配置文件中注入对象的id值 -->
    <constructor-arg name="studentDao" ref="studentDao"></constructor-arg>
</bean>
DI_依赖注入类型

DI支持注入bean类型、基本数据类型和字符串、List集合、Set集合、Map集合、Properties对象类型等

 <!--    集合类型装配-->
    <bean id="somebean" class="ioc03.SomeBean">
        <property name="list">
            <list>
                <!--<ref></ref>
                <bean></bean>-->
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
         <!-- 对象类型List集合 name:属性名,set也一样 -->
    <property name="students1">
        <list>
            <bean class="entity.Student">
                <property name="id" value="1"/>
                <property name="name" value="hhh"/>
                <property name="address" value="lll"/>
             </bean>
              <bean class="entity.Student">
                <property name="id" value="2"/>
                <property name="name" value="kkk"/>
                <property name="address" value="lll"/>
             </bean>
        </list>
    </property>
        <property name="set">
            <set>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </set>
        </property>
        <property name="map">
            <map>
                <entry key="aaa">
                    <value>111</value>
                </entry>
                <entry key="bbb">
                    <value>222</value>
                </entry>
                <entry key="ccc">
                    <value>333</value>
                </entry>
            </map>
		 <!-- 对象类型map集合 ,其中s1为bean对象,通过id获取-->
        <map>
            <entry key="student1" value-ref="s1"/>
        </map>
        <property name="properties">
            <props>
                <prop key="aaa">111</prop>
                <prop key="bbb">222</prop>
                <prop key="ccc">333</prop>
            </props>
        </property>
        <property name="arrays">
            <list>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </list>
        </property>
    </bean>

注解实现 IOC_准备工作

注解配置和xml配置对于Spring的IOC要实现的功能都是一样的,只是配置的形式不一样。

准备工作
  • 编写空的配置文件,如果想让该文件支持注解,需要添加新的约束:
  • xmlns:context=“http://www.springframework.org/schema/context”

  • http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

@Component

作用:用于创建对象,放入Spring容器,相当于 <bean id="" class="">
位置:类上方
注意:

  • 要在配置文件中配置扫描的包,扫描到该注解才能生效。<context:component-scan basepackage="com.itbaizhan"</context:component-scan>
  • @Component 注解配置bean的默认id是首字母小写的类名。也可以手动设置bean的id值。
// 此时bean的id为studentDaoImpl
 @Component
 public class StudentDaoImpl implements
	StudentDao{
    public Student findById(int id) {
       // 模拟根据id查询学生
        return new Student(1,"程序员","加拿大");
   }
// 此时bean的id为studentDao
@Component("studentDao")
public class StudentDaoImpl implements
StudentDao{
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"程序员","德国");
   }
}
@Repository、@Service、@Controller

作用:这三个注解和@Component的作用一样,使用它们是为了区分该类属于什么层。

  • @Repository用于Dao层
  • @Service用于Service层
  • @Controller用于Controller层
@Scope

作用:指定bean的创建策略@Scope("singleton")
位置:类上方
取值:singleton prototype request session globalsession

@Autowired ***

作用:从容器中查找符合属性类型的对象自动注入属性中。用于代替 <bean> 中的依赖注入配置
位置:属性上方、setter方法上方、构造方法上方。
注意:

  • @Autowired 写在属性上方进行依赖注入时,可以省略setter方法
  • @Autowired
    private StudentDao studentDao;

  • 容器中没有对应类型的对象会报错
  • 容器中有多个对象匹配类型时,会找beanId等于属性名的对象,找不到会报错。
@Qualifier

作用:在按照类型注入对象的基础上,再按照bean的id注入。
位置:属性上方
注意:@Qualifier必须和@Autowired一起使用。

@Component
2 public class StudentService {
3 @Autowired
4 @Qualifier(“studentDaoImpl2”)
5 private StudentDao studentDao;
6 public Student findStudentById(int id){
7 return studentDao.findById(id);
8 }
9 }

@Resource(name = “studentDaoImpl2”)

相当于 自动注解加修饰词

@Value

作用:注入String类型和基本数据类型的属性值。
位置:属性上方
用法:

  • 直接设置固定的属性值
  • @Service
    public class StudentService {
    @Value(“1”)
    private int count;
    @Value(“hello”)
    private String str;
    }

  • 获取配置文件中的属性值:
    • 编写配置文件db.properties
    • jdbc.username=root
      jdbc.password=123456

    • spring核心配置文件扫描配置文件
    • <context:property-placeholder location=“db.properties”></context:property-placeholder>

    • 注入配置文件中的属性值${key}
    • @Value(“$ j d b c . u s e r n a m e " ) p r i v a t e S t r i n g u s e r n a m e ; @ V a l u e ( " {jdbc.username}") private String username; @Value(" jdbc.username")privateStringusername;@Value("{jdbc.password}”)
      private String password;

@Configuration

此时基于注解的IOC配置已经完成,但是我们依然离不开Spring的xml配置文件。接下来我们脱离bean.xml,使用纯注解实现IOC。

在真实开发中,我们一般还是会保留xml配置文件,很多情况下使用配置文件更加方便。

纯注解实现IOC需要一个Java类代替xml文件。这个Java类上方需要添加@Configuration,表示该类是一个配置类,作用是代替配置文件。

@Configuration
public class SpringConfig {  
}
@ComponentScan

作用:指定spring在初始化容器时扫描的包。
位置:配置类上方

@Configuration
// 可以放多个 value= {"dao","service"}
@ComponentScan("dao")
public class SpringConfig {
}
@PropertySource

作用:代替配置文件中的 <context:property-placeholder> 扫描配置文件
位置:配置类上方
注意:配置文件位置前要加关键字 classpath

@Configuration
@PropertySource("classpath:db.properties")
public class JdbcConfig {
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
}
@Bean

作用:将方法的返回值对象放入Spring容器中。如果想将第三方类的对象放入容器,可以使用@Bean
位置:配置类的方法上方。
属性:name:给bean对象设置id
注意:@Bean修饰的方法如果有参数,spring会根据参数类型从容器中查找可用对象。
举例:如果想将jdbc连接对象放入Spring容器,我们无法修改Connection源码添加@Component,此时就需要使用将@Bean该对象放入Spring容器

@Configuration
@ComponentScan(value = {"dao","service"})
public class SpringConfig {

    @Bean(name = "conn")
    public Connection getConnection(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/maven?useUnicode=true&characterEncoding=utf8","root","123");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
@Import

作用:如果配置过多,会有多个配置类,该注解可以为主配置类导入其他配置类
位置:主配置类上方

// 主配置类
@Configuration
@Import(JdbcConfig.class)
public class SpringConfig {
}
// Jdbc配置类
@Configuration
public class JdbcConfig {
}

Spring整合MyBatis

用Spring整合MyBatis,简化MyBatis开发。

搭建环境

创建maven项目,引入依赖
<!--    mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
<!--    驱动依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>
    <!--阿里的连接池 druid-->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.2.16</version>
      </dependency>
<!--    spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.27</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.13</version>
    </dependency>
<!--    spring于mybatis整合包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>
  </dependencies>
Spring整合MyBatis_编写配置文件
  • 编写数据库配置文件db.properties
  • jdbc.driverclassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql:///student
    jdbc.username=root
    jdbc.password=123

  • 创建MyBatis配置文件SqlMapConfig.xml,数据源、扫描接口都交由Spring管理,不需要在MyBatis配置文件中设置。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--    <mappers>-->
<!--        <mapper class="com.zzh.dao.StudentDao"></mapper>-->
<!--    </mappers>-->
</configuration>
  • 创建Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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.zzh"></context:component-scan>
    <!--    读取配置文件-->
    <context:property-placeholder location="db.properties"></context:property-placeholder>
    <!--新建连接池数据源对象-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverclassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--创建Spring封装过的sqlsessionfactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
<!--        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>-->
    </bean>
    <!--    创建Spring封装过的sqlsession对象-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    </bean>
</beans>

准备数据库和实体类

自己创建数据库,插入数据 student{id,name,sex,address}
编写持久层接口
@Repository
public interface StudentDao {
    /**
     * 采用注解添加
     * @return
     */
    // 查询所有学生
    @Select("select * from student")
    List<Student> findAll();

    // 添加学生
    @Insert("insert into student (name,sex,address) values (#{name},#{sex},#{address})")
    void addStudent(Student student);
}

编写service类
@Service
public class StudentService {
    @Autowired
    private SqlSessionTemplate sqlSession;

    // 使用sqlsession获取代理对象操作数据库
    public List<Student> findALlStudent(){
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        return dao.findAll();
    }
}
Spring整合Junit进行单元测试

通过注解形式自动创建容器,不用每次重写

  • 引入Junit和Spring整合Junit依赖
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>5.3.13</version>
      </dependency>
编写测试类
// junit使用spring的方式运行代码,自动创建spring容器
@RunWith(SpringJUnit4ClassRunner.class)
//spring容器创建时读取配置文件
// 配置类的写法
//@ContextConfiguration(classes = ".....class")
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class StudentServiceTest {
    @Autowired
    private StudentService service;
    @Test
    public void testFindAll(){
        List<Student> list = service.findALlStudent();
        for (Student student : list) {
            System.out.println(student);
        }
    }
}

知识点
  • 注:使用SqlSessionTemplate创建代理对象还是需要注册接口或者映射文件的。
// 在Sql配置文件中 注册接口
<configuration>

    <mappers>
        <mapper class="com.zzh.dao.StudentDao"></mapper>
    </mappers>
</configuration>

// 创建sqlSessionFactory时指定MyBatis配置文件
    <!--创建Spring封装过的sqlsessionfactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
    </bean>

自动创建代理对象

Spring提供了MapperScannerConfigurer对象,该对象可以自动扫描包创建代理对象,并将代理对象放入容器中,此时不需要使用SqlSession手动创建代理对象。这样的话就不需要读取mybatis配置文件注册接口.

  • 创建MapperScannerConfigurer对象
<!--    扫描 持久层接口,并为接口创建代理对象-->
    <bean id="mapperSacnner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zzh.dao"></property>
     </bean>
// Service类直接使用代理对象即可

public class StudentService {
    // 直接注入代理对象
    @Autowired
    private StudentDao studentDao;
  
    // 直接使用代理对象
    public void addStudent(Student
student){
        studentDao.add(student);
   }
}

SpringAOP_AOP简介

AOP的全称是Aspect Oriented Programming,即面向切面编程。是实现功能统一维护的一种技术,它将业务逻辑的各个部分进行隔离,使开发人员在编写业务逻辑时可以专心于核心业务,从而提高了开发效率。

  • 作用:在不修改源码的基础上,对已有方法进行增强。
  • 实现原理:动态代理技术。
  • 优势:减少重复代码、提高开发效率、维护方便
  • 应用场景:事务处理、日志管理、权限控制、异常处理等方面。

AOP相关术语

名称说明
joinpoint(连接点)指能被拦截到的点,在Spring中只有方法能被拦截。
pointCut(切入点)指要对哪些连接点进行拦截,即被增强的方法。
Advice(通知)指拦截后要做的事情,即切点被拦截后执行的方法。
Aspect(切面)切点+通知称为切面
Target(目标)被代理对象
Proxy(代理)代理对象
weaving(织入)生成代理对象的过程

通知类型

  • 前置通知 在方法执行前添加功能
  • 后置通知 在方法正常执行后添加功能
  • 异常通知 在方法抛出异常后添加功能
  • 最终通知 无论方法是否抛出异常,都会执行该通知
  • 环绕通知 在方法执行前后添加功能

AOP入门

AspectJ是一个基于Java语言的AOP框架,在Spring框架中建议使用AspectJ实现AOP。

引入依赖
dependency>
    <groupId>org.springframework</groupId>
    <artifactId>springcontext</artifactId>
    <version>5.3.13</version>
</dependency>
<!-- AspectJ -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
</dependency>
编写连接点
@Repository
public class UserDao {
    public void add(){
        int x = 1/0;
        System.out.println("用户新增");
    }
    public void delete(){
        System.out.println("用户删除");
    }
    public void update(){
        System.out.println("用户修改");
    }
}

编写通知类Aspectj
package com.zzh.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

// 通知类
public class MyAspectAdvice {
    // 后置通知
    public void myAfterReturning(JoinPoint joinPoint){
        System.out.println("切点方法名:"+joinPoint.getSignature().getName());
        System.out.println("目标对象:"+joinPoint.getTarget());
        System.out.println("打印日志"+joinPoint.getSignature().getName()+"方法被执行了");
    }

    // 前置通知
    public void myBefore(){
        System.out.println("前置通知");
    }
    //异常通知
    public void myAfterThrowing(Exception e){
        System.out.println("异常通知");
        System.out.println(e.getMessage());
    }

    //最终通知
    public void myAspectFinally(){
        System.out.println("最终通知");
    }

    // 环绕通知
    public Object mySurround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕前");
        Object obj = proceedingJoinPoint.proceed(); //执行方法
        System.out.println("环绕后");
        return obj;
    }
}

配置切面
<!--    扫描dao包添加bean对象-->
    <context:component-scan base-package="com.zzh.dao"></context:component-scan>
<!--    通知对象-->
    <bean id="myAspectAdvice" class="com.zzh.advice.MyAspectAdvice"></bean>
<!--    配置aop,添加aop约束-->
    <aop:config>
<!--        配置切面-->
        <aop:aspect ref="myAspectAdvice">
<!--            配置切点-->
            <aop:pointcut id="mypointCut" expression="execution(* com.zzh.dao.UserDao.*(..))"/>
<!--            配置通知-->
<!--            前置通知-->
<!--            <aop:before method="myBefore" pointcut-ref="mypointCut"/>-->
<!--            后置通知-->
<!--            <aop:after-returning method="myAfterReturning" pointcut-ref="mypointCut"></aop:after-returning>-->
<!--            异常通知-->
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="mypointCut" throwing="e"/>
<!--            最终通知-->
            <aop:after  method="myAspectFinally" pointcut-ref="mypointCut"/>
<!--            环绕通知-->
<!--            <aop:around method="mySurround" pointcut-ref="mypointCut"/>-->

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

切点表达式

访问修饰符 返回值 包名.类名.方法名(参数列表)
(修饰符可以省略) * *..*.*(..);

多切面配置

多配置几次切面就可以

注解配置AOP

Spring可以使用注解代替配置文件配置切面:

  • 在xml文件开启AOP注解支持
  • <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  • 在通知类上添加注解@Aspect
  • 在通知方法上添加注解@Before/@AfterReturning/@AfterThrowing/@After/@Around
  • @AfterReturning("execution(*com.itbaizhan.dao.UserDao.*(..))")
  • 所有方法统一配置切点:
    • 在通知类中添加方法配置切点
    • @Pointcut(“execution(com.itbaizhan.dao.UserDao.(…))”)public void pointCut(){}

    • @Before(“pointCut()”)
  • 在配置类上方添加@EnableAspectJAutoProxy即可

未完成

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值