Spring-全面详解(学习总结---从入门到深化)

news2024/10/6 5:55:31

目录

Spring简介

 Spring体系结构

IOC_控制反转思想 

IOC_自定义对象容器

 IOC_Spring实现IOC

 IOC_Spring容器类型                                                                     ​                

容器实现类

 IOC_对象的创建方式

使用构造方法

使用工厂类的方法

使用工厂类的静态方法

IOC_对象的创建策略

 IOC_对象的销毁时机

 IOC_生命周期方法

IOC_获取Bean对象的方式

通过id/name获取

通过类型获取

通过类型+id/name获取

DI_什么是依赖注入

DI_依赖注入方式

Setter注入

构造方法注入

自动注入

DI_依赖注入类型

注入bean类型

注入基本数据类型

注入List集合

注入Set集合

注入Map集合

注入Properties对象

注解实现IOC_准备工作

注解实现IOC_@Component

 注解实现IOC_@Repository、@Service、@Controller

注解实现IOC_@Scope

注解实现IOC_@Autowired 

注解实现IOC_@Qualifier 

注解实现IOC_@Value

注解实现IOC_@Configuration 

注解实现IOC_@ComponentScan

 注解实现IOC_@PropertySource

注解实现IOC_@Bean

注解实现IOC_@Import 

Spring整合MyBatis_搭建环境

创建maven项目,引入依赖。

Spring整合MyBatis_编写配置文件

 1、编写数据库配置文件db.properties

 Spring整合MyBatis_准备数据库和实体类

准备数据库

准备实体类

Spring整合MyBatis_编写持久层接口和service类

编写持久层接口

编写service类

Spring整合MyBatis_Spring整合Junit进行单元测试

Spring整合MyBatis_自动创建代理对象 

SpringAOP_AOP简介 

 SpringAOP_AOP相关术语

 SpringAOP_AOP入门

 SpringAOP_通知类型

SpringAOP_切点表达式 

SpringAOP_多切面配置 

 SpringAOP_注解配置AOP

SpringAOP_原生Spring实现AOP

SpringAOP_SchemaBased实现AOP 

Spring事务_事务简介

Spring事务_Spring事务管理方案 

 Spring事务_Spring事务管理器

Spring事务_事务控制的API

Spring事务_事务的相关配置 

 Spring事务_事务的传播行为

Spring事务_事务的隔离级别 

 Spring事务_注解配置声明式事务

Spring简介

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

Spring官网地址:https://spring.io/

 Spring体系结构

 Spring框架根据不同的功能被划分成了多个模块,这些模块可以满 足一切企业级应用开发的需求,在开发过程中可以根据需求有选择 性地使用所需要的模块。

1、Core Container:Spring核心模块,任何功能的使用都离不开该模块,是其他模块建立的基础。

2、Data Access/Integration:该模块提供了数据持久化的相应功能。

3、Web:该模块提供了web开发的相应功能。

4、AOP:提供了面向切面编程实现

5、Aspects:提供与AspectJ框架的集成,该框架是一个面向切面编程框架。

6、Instrumentation:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使 用。

7、Messaging:为Spring框架集成一些基础的报文传送应用

8、Test:提供与测试框架的集成

IOC_控制反转思想 

 IOC(Inversion of Control) :程序将创建对象的权利交给框架。 之前在开发过程中,对象实例的创建是由调用者管理的,代码如下:

public interface StudentDao {
    // 根据id查询学生
    Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
    @Override
    public Student findById(int id) {
        // 模拟从数据库查找出学生
        return new Student(1,"程序员","北京");
   }
}
public class StudentService {
    public Student findStudentById(int id){
        // 此处就是调用者在创建对象
        StudentDao studentDao = new StudentDaoImpl();
        return studentDao.findById(1);
   }
}

这种写法有两个缺点:

1 浪费资源:StudentService调用方法时即会创建一个对象,如果 不断调用方法则会创建大量StudentDao对象。

2 代码耦合度高:假设随着开发,我们创建了StudentDao另一个 更加完善的实现类StudentDaoImpl2,如果在StudentService 中想使用StudentDaoImpl2,则必须修改源码。

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

IOC_自定义对象容器

 接下来我们通过一段代码模拟IOC思想。创建一个集合容器,先将 对象创建出来放到容器中,需要使用对象时,只需要从容器中获取 对象即可,而不需要重新创建,此时容器就是对象的管理者。

创建实体类

public class Student {
    private int id;
    private String name;
    private String address;
 // 省略getter/setter/构造方法/tostring
}

创建Dao接口和实现类

public interface StudentDao {
    // 根据id查询学生
    Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
    @Override
    public Student findById(int id) {
        // 模拟从数据库查找出学生
        return new Student(1,"程序员","北京");
   }
}
public class StudentDaoImpl2 implements StudentDao{
    @Override
    public Student findById(int id) {
        // 模拟根据id查询学生
        System.out.println("新方法!!!");
        return new Student(1,"程序员","北京");
   }
}

创建配置文件bean.properties,该文件中定义管理的对象

studentDao=com.itbaizhan.dao.StudentDaoImpl

创建容器管理类,该类在类加载时读取配置文件,将配置文件中 配置的对象全部创建并放入容器中。

public class Container {
    static Map<String,Object> map = new HashMap();
    static {
        // 读取配置文件
        InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
       } catch (IOException e) {
            e.printStackTrace();
       }
        // 遍历配置文件的所有配置
        Enumeration<Object> keys = properties.keys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement().toString();
            String value = properties.getProperty(key);
            try {
                // 创建对象
                Object o = Class.forName(value).newInstance();
                // 将对象放入集合中
                map.put(key,o);
           } catch (Exception e) {
                e.printStackTrace();
           }
       }
   }
    // 从容器中获取对象
 public static Object getBean(String key){
        return map.get(key);
   }
}

创建Dao对象的调用者StudentService

public class StudentService {
    public Student findStudentById(int id)
     {
        // 从容器中获取对象
        StudentDao studentDao = (StudentDao) Container.getBean("studentDao");
        System.out.println(studentDao.hashCode());
        return studentDao.findById(id);
   }
}

测试StudentService

public class Test {
    public static void main(String[] args)
    {
      StudentService studentService = new StudentService();
      System.out.println(studentService.findStudentById(1));
      System.out.println(studentService.findStudentById(1));
   }
}

 IOC_Spring实现IOC

 接下来我们使用Spring实现IOC,Spring内部也有一个容器用来管 理对象。

创建Maven工程,引入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

创建POJO类、Dao类和接口

public class Student {
    private int id;
    private String name;
    private String address;
  // 省略getter/setter/构造方法/tostring
}
public interface StudentDao {
    // 根据id查询学生
    Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
    @Override
    public Student findById(int id) {
        // 模拟从数据库查找出学生
        return new Student(1,"程序员","北京");
   }
}

编写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 id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>     
</beans>

 测试从Spring容器中获取对象。            

public class TestContainer {
    @Test
    public void t1(){
        // 创建Spring容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        // 从容器获取对象
        StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");
        StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");
        System.out.println(studentDao1.hashCode());
        System.out.println(studentDao2.hashCode());
        System.out.println(studentDao1.findById(1));
   }
}

 IOC_Spring容器类型                                                                     容器接口                            

 1、BeanFactory:BeanFactory是Spring容器中的顶层接口,它可 以对Bean对象进行管理。

2、ApplicationContext:ApplicationContext是BeanFactory的子 接口。它除了继承 BeanFactory的所有功能外,还添加了对国际 化、资源访问、事件传播等方面的良好支持。

 ApplicationContext有以下三个常用实现类:、

容器实现类

1、ClassPathXmlApplicationContext:该类可以从项目中读取配置文件

2、FileSystemXmlApplicationContext:该类从磁盘中读取配置文件

3、AnnotationConfigApplicationContext:使用该类不读取配置文件,而是会读取注解

@Test
public void t2(){
    // 创建spring容器
    //       ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\a\\IdeaProjects\\spring_demo\\src\\main\\resources\\bean.xml");
    
    // 从容器中获取对象
    StudentDao userDao = (StudentDao)ac.getBean("studentDao");
    System.out.println(userDao);
    System.out.println(userDao.findById(1));
}

 IOC_对象的创建方式

 Spring会帮助我们创建bean,那么它底层是调用什么方法进行创建 的呢?

使用构造方法

Spring默认使用类的空参构造方法创建bean:

// 假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements StudentDao{
    public StudentDaoImpl(int a){}    
    @Override
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"程序员","北京");
   }
}

使用工厂类的方法

Spring可以调用工厂类的方法创建bean:

1、创建工厂类,工厂类提供创建对象的方法:

public class StudentDaoFactory {
    public StudentDao getStudentDao(){
        return new StudentDaoImpl(1);
   }
}

2 在配置文件中配置创建bean的方式为工厂方式。

<!-- id:工厂对象的id,class:工厂类 -->
<bean id="studentDaoFactory" class="com.itbaizhan.dao.StudentDaoFactory"></bean>
<!-- id:bean对象的id,factory-bean:工厂对象 的id,factory-method:工厂方法 -->
<bean id="studentDao" factorybean="studentDaoFactory" factory-method="getStudentDao"></bean>

3 测试

使用工厂类的静态方法

Spring可以调用工厂类的静态方法创建bean:

1 创建工厂类,工厂提供创建对象的静态方法。

public class StudentDaoFactory2 {
    public static StudentDao getStudentDao2() {
        return new StudentDaoImpl();
   }
}

2 在配置文件中配置创建bean的方式为工厂静态方法。

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

3 测试

IOC_对象的创建策略

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

1、singleton:单例,默认策略。整个项目只会创建一个对象,通过中的 lazy-init 属性可以设置单例对象的创建时机:

 lazy-init="false"(默认):立即创建,在容器启动时会创建配 置文件中的所有Bean对象。 lazy-init="true":延迟创建,第一次使用Bean对象时才会创 建。

 配置单例策略:

<!--   <bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" lazy-init="true"> </bean>-->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" lazy-init="false">
</bean>

测试单例策略:

// 为Bean对象的类添加构造方法
public StudentDaoImpl2(){
    System.out.println("创建 StudentDao!!!");
}
@Test
public void t2(){
    // 创建Spring容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
    // 从容器获取对象
    StudentDao studentDao1 = (StudentDao)ac.getBean("studentDao");
    StudentDao studentDao2 = (StudentDao)ac.getBean("studentDao");
    StudentDao studentDao3 = (StudentDao)ac.getBean("studentDao");
    System.out.println(studentDao1.hashCode());
    System.out.println(studentDao2.hashCode());
    System.out.println(studentDao3.hashCode());
}

2、prototype:多例,每次从容器中获取时都会创建对象。

<!-- 配置多例策略 -->
<bean id="studentDao"  class="com.itbaizhan.dao.StudentDaoImpl2" scope="prototype"></bean>

3、request:每次请求创建一个对象,只在web环境有效。

4、session:每次会话创建一个对象,只在web环境有效。

5、gloabal-session:一次集群环境的会话创建一个对象,只在web 环境有效。

 IOC_对象的销毁时机

 对象的创建策略不同,销毁时机也不同:

singleton:对象随着容器的销毁而销毁。

prototype:使用JAVA垃圾回收机制销毁对象。

request:当处理请求结束,bean实例将被销毁。

session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。

gloabal-session:集群环境下的session销毁,bean实例也将被销毁。

 IOC_生命周期方法

 Bean对象的生命周期包含创建——使用——销毁,Spring可以配置 Bean对象在创建和销毁时自动执行的方法:

1 定义生命周期方法

public class StudentDaoImpl2 implements StudentDao{
     // 创建时自动执行的方法
    public void init(){
        System.out.println("创建StudentDao!!!");
   }
    // 销毁时自动执行的方法
    public void destory(){
        System.out.println("销毁StudentDao!!!");
   }
}

2 配置生命周期方法

<!-- init-method:创建对象时执行的方法  destroy-method:销毁对象时执行的方法 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton"
      init-method="init" destroy-method="destory"></bean>

3 测试

@Test
public void t3(){
    // 创建Spring容器
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
    // 销毁Spring容器,ClassPathXmlApplicationContext才有销毁容器的方法
    ac.close();
}

IOC_获取Bean对象的方式

 Spring有多种获取容器中对象的方式:

通过id/name获取

配置文件

<bean name="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean>
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean>

获取对象

StudentDao studentDao = (StudentDao) ac.getBean("studentDao");

通过类型获取

配置文件

<bean name="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean>

获取对象

StudentDao studentDao2 = ac.getBean(StudentDao.class);

通过类型+id/name获取

虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个 实现类对象,则获取时会报错,此时需要使用类型+id/name获取

配置文件

<bean name="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2"></bean>
<bean name="studentDao1" class="com.itbaizhan.dao.StudentDaoImpl"></bean>

获取对象

StudentDao studentDao2 = ac.getBean("studentDao",StudentDao.class);

DI_什么是依赖注入

 依赖注入(Dependency Injection,简称DI),它是Spring控制反 转思想的具体实现。 控制反转将对象的创建交给了Spring,但是对象中可能会依赖其他 对象。比如service类中要有dao类的属性,我们称service依赖于 dao。之前需要手动注入属性值,代码如下:

public interface StudentDao {
    Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
    @Override
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"程序员","北京");
   }
}
public class StudentService {
  // service依赖dao,手动注入属性值,即手动维护依赖关系
    private StudentDao studentDao = new StudentDaoImpl();
    public Student findStudentById(int id){
        return studentDao.findById(id);
   }
}

此时,当StudentService的想要使用StudentDao的另一个实现类如 StudentDaoImpl2时,则需要修改Java源码,造成代码的可维护性 降低。 而使用Spring框架后,Spring管理Service对象与Dao对象,此时它 能够为Service对象注入依赖的Dao属性值。这就是Spring的依赖注 入。简单来说,控制反转是创建对象,依赖注入是为对象的属性赋 值。

DI_依赖注入方式

 在之前开发中,可以通过setter方法或构造方法设置对象属性值:

// setter方法设置属性
StudentService studentService = new StudentService();
StudentDao studentDao = new StudentDao();
studentService.setStudentDao(studentDao);
// 构造方法设置属性
StudentDao studentDao = new StudentDao();
StudentService studentService = new StudentService(studentDao);

Spring可以通过调用setter方法或构造方法给属性赋值

Setter注入

被注入类编写属性的setter方法

public class StudentService {
    private StudentDao studentDao;
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
   }
}

配置文件中,给需要注入属性值的<bean> 中设置<property>

<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <!--依赖注入-->
    <!--name:对象的属性名 ref:容器中对象的id值-->
    <property name="studentDao" ref="studentDao"></property>
</bean>

测试是否注入成功

@Test
public void t2(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    StudentService studentService = (StudentService) ac.getBean("studentService");
    System.out.println(studentService.findStudentById(1));
}

构造方法注入

被注入类编写有参的构造方法

public class StudentService {
    private StudentDao studentDao;
    public StudentService(StudentDao studentDao) {
        this.studentDao = studentDao;
   }
}

给需要注入属性值的<bean> 中设置<constructor-arg>

<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <!-- 依赖注入 -->
    <!-- name:对象的属性名 ref:配置文件中注入对象的id值 -->
    <constructor-arg name="studentDao" ref="studentDao"></constructor-arg>
</bean>

测试是否注入成功

@Test
public void t2(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    StudentService studentService =(StudentService) ac.getBean("studentService");
  System.out.println(studentService.findStudentById(1));
}

自动注入

 自动注入不需要在 标签中添加其他标签注入属性值,而是自 动从容器中找到相应的bean对象设置为属性值。

 

 测试自动注入:

    1、为依赖的对象提供setter和构造方法:

public class StudentService {
     // 依赖
     private StudentDao studentDao;
     // 构造方法
     public StudentService() { }
    
    public StudentService(StudentDao studentDao) {
        this.studentDao = studentDao;
   }
    // setter方法
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
   }
    // 调用依赖的方法
    public Student findStudentById(int id)
      {
        return studentDao.findById(id);
      }
}

2、配置自动注入:

<!-- 根据beanId等于属性名自动注入 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="byName"></bean>
<!-- 根据bean类型等于属性类型自动注入 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="byType"></bean>
<!-- 利用构造方法自动注入 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService" autowire="constructor"></bean>
<!-- 配置全局自动注入 -->
<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"
        default-autowire="constructor">

DI_依赖注入类型

 DI支持注入bean类型、基本数据类型和字符串、List集合、Set集合、Map集合、Properties对象类型等,他们的写法如下:

1、准备注入属性的类

public class StudentService {
    private StudentDao studentDao; // bean属性

    private String name; //字符串类型

    private int count; //基本数据类型

    private List<String> names; // 字符串类型List集合

    private List<Student> students1; // 对象类型List集合

    private Set<Student> students2; // 对象类型Set集合

    private Map<String,String> names2; //字符串类型Map集合

    private Map<String,Student> students3;// 对象类型Map集合

    private Properties properties;//Properties类型

    // 省略getter/setter/toString
}

2、准备测试方法

@Test
public void t3(){
    ApplicationContext ac = newClassPathXmlApplicationContext("bean.xml");
    StudentService studentService =(StudentService)ac.getBean("studentService");
    System.out.println(studentService);
}

注入bean类型

写法一:

<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <property name="studentDao" ref="studentDao"></property>
</bean>

写法二:

<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <property name="studentDao" >
        <ref bean="studentDao"></ref>
    </property>
</bean>

注入基本数据类型

<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <!-- 写法一 name:属性名 value:属性值-->
    <property name="name" value="百百">
</property>
    <!-- 写法二 name:属性名 value:属性值-->
    <property name="count">
        <value>10</value>
    </property>
</bean>

注入List集合

<bean id="studentService"
class="com.itbaizhan.service.StudentService">
    <!-- 简单数据类型List集合 name:属性名 -->
    <property name="names">
        <list>
            <value>强学堂</value>
            <value>程序员</value>
        </list>
    </property>
    <!-- 对象类型List集合 name:属性名 -->
    <property name="students1">
        <list>
            <bean class="com.itbaizhan.domain.Student">
                <property name="id" value="1"/>
                <property name="name" value="强学堂"/>
                <property name="address" value="北京"/>
            </bean>
            <bean class="com.itbaizhan.domain.Student">
                <property name="id" value="2"/>
                <property name="name" value="百战不败"/>
                <property name="address" value="北京"/>
            </bean>
        </list>
    </property>
</bean>

注入Set集合

<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <!-- Set集合 -->
    <property name="students2">
        <set>
            <bean class="com.itbaizhan.domain.Student">
                <property name="id" value="1"/>
                <property name="name" value="强学堂"/>
                <property name="address" value="北京"/>
            </bean>
            <bean class="com.itbaizhan.domain.Student">
                <property name="id" value="2"/>
                <property name="name" value="百战不败"/>
                <property name="address" value="北京"/>
            </bean>
        </set>
    </property>
</bean>

注入Map集合

简单数据类型Map集合:

<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <property name="names2">
        <map>
            <entry key="student1" value="bz"/>
            <entry key="student2" value="sxt"/>
        </map>
    </property>
</bean>

对象类型Map集合:

<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <property name="students3">
        <map>
            <entry key="student1" value-ref="s1"/>
            <entry key="student2" value-ref="s2"/>
        </map>
    </property>
</bean>
<bean id="s1" class="com.itbaizhan.domain.Student">
    <property name="id" value="1"/>
    <property name="name" value="强学堂"/>
    <property name="address" value="北京"/>
</bean>
<bean id="s2" class="com.itbaizhan.domain.Student">
    <property name="id" value="2"/>
    <property name="name" value="百战不败"/>
    <property name="address" value="北京"/>
</bean>

注入Properties对象

<bean id="studentService" class="com.itbaizhan.service.StudentService">
    <property name="properties">
        <props>
            <prop key="配置1">值1</prop>
            <prop key="配置2">值2</prop>
        </props>
    </property>
</bean>

注解实现IOC_准备工作

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

准备工作

1 创建一个新的Spring项目。

2 编写pojo,dao,service类。

3 编写空的配置文件,如果想让该文件支持注解,需要添加新的约束:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      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
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

注解实现IOC_@Component

 作用:用于创建对象,放入Spring容器,相当于

 位置:类上方

 注意:

     1、要在配置文件中配置扫描的包,扫描到该注解才能生效。

<context:component-scan base-package="com.itbaizhan"></context:component-scan>

   2、@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,"程序员","北京");
   }
}

 注解实现IOC_@Repository、@Service、@Controller

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

位置:

1、@Repository用于Dao层

2、@Service用于Service层

3、@Controller用于Controller层

@Repository
public class StudentDaoImpl implements StudentDao{}
@Service
public class StudentService {}

注解实现IOC_@Scope

 作用:指定bean的创建策略

位置:类上方

取值:singleton prototype request session globalsession

@Service
@Scope("singleton")
public class StudentService {}

注解实现IOC_@Autowired 

作用:从容器中查找符合属性类型的对象自动注入属性中。用于代替<bean> 中的依赖注入配置。

位置:属性上方、setter方法上方、构造方法上方。

注意:  

       1、@Autowired 写在属性上方进行依赖注入时,可以省略setter方法。

       

@Component
public class StudentService {
    @Autowired
    private StudentDao studentDao;
    public Student findStudentById(int id)
     {
        return studentDao.findById(id);
     }
}
@Test
public void t2(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    StudentService studentService =(StudentService)ac.getBean("studentService");
  System.out.println(studentService.findStudentById(1));
}

      2、容器中没有对应类型的对象会报错

// 如果StudentDaoImpl没有放到容器中会报错
//@Component("studentDao")
public class StudentDaoImpl implements StudentDao{
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"程序员","北京");
   }
}

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

// 如果容器中都多个同类型对象,会根据id值等于属性
名找对象
@Component("studentDao")
public class StudentDaoImpl implements StudentDao{
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"程序员","北京");
   }
}
@Component
public class StudentDaoImpl implements StudentDao{
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"程序员","北京");
 }
}

注解实现IOC_@Qualifier 

 

 作用:在按照类型注入对象的基础上,再按照bean的id注入。

位置:属性上方

注意:@Qualifier必须和@Autowired一起使用。

@Component
public class StudentService {
    @Autowired
    @Qualifier("studentDaoImpl2")
    private StudentDao studentDao;
    public Student findStudentById(int id){
        return studentDao.findById(id);
   }
}

注解实现IOC_@Value

 作用:注入String类型和基本数据类型的属性值。

位置:属性上方

用法:

        1 、直接设置固定的属性值

@Service
public class StudentService {
    @Value("1")
    private int count;
    @Value("hello")
    private String str;
}

        2 、获取配置文件中的属性值:

                 2.1 、编写配置文件db.properties

                  

jdbc.username=root
jdbc.password01=123456

                 2.2、spring核心配置文件扫描配置文件

                 

<context:property-placeholder location="db.properties">
</context:property-placeholder>

                2.3 注入配置文件中的属性值

@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;

注解实现IOC_@Configuration 

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

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

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

@Configuration
public class SpringConfig {  
}

注解实现IOC_@ComponentScan

作用:指定spring在初始化容器时扫描的包。

位置:配置类上方

@Configuration
@ComponentScan("com.itbaizhan")
    public class SpringConfig { }

 注解实现IOC_@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;
}

注解实现IOC_@Bean

作用:将方法的返回值对象放入Spring容器中。如果想将第三方类 的对象放入容器,可以使用@Bean

位置:配置类的方法上方。

属性:name:给bean对象设置id

注意:@Bean修饰的方法如果有参数,spring会根据参数类型从容 器中查找可用对象。

举例:如果想将jdbc连接对象放入Spring容器,我们无法修改 Connection源码添加@Component,此时就需要使用将@Bean该 对象放入Spring容器

 1 、添加驱动依赖

    

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.27</version>
</dependency>

2、将Connection对象放入Spring容器

@Bean(name = "connection")
public Connection getConnection(){
    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
        returnDriverManager.getConnection("jdbc:mysql:///mysql", "root", "root");
   } catch (Exception exception) {
        return null;
   }
}

3、测试

@Test
public void t5(){
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
    Connection connection = (Connection)ac.getBean("connection");
    System.out.println(connection);
}

注解实现IOC_@Import 

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

 位置:主配置类上方

// Jdbc配置类
@Configuration
public class JdbcConfig {
    @Bean(name = "connection")
    public Connection getConnection(){
        try {
          Class.forName("com.mysql.cj.jdbc.Driver");
          return DriverManager.getConnection("jdbc:mysql:///mysql", "root", "root");
       } catch (Exception exception) {
            return null;
       }
   }
}
// 主配置类
@Configuration
@ComponentScan("com.itbaizhan")
@Import(JdbcConfig.class)
public class SpringConfig { }

Spring整合MyBatis_搭建环境

 我们知道使用MyBatis时需要写大量创建 SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession等对 象的代码,而Spring的作用是帮助我们创建和管理对象,所以我们 可以使用Spring整合MyBatis,简化MyBatis开发。

创建maven项目,引入依赖。

<dependencies>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>

    <!-- mysql驱动包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>

    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.13</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>

    <!-- MyBatis与Spring的整合包,该包可以让Spring创建MyBatis的对象 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
</dependencies>

Spring整合MyBatis_编写配置文件

 1、编写数据库配置文件db.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///student
jdbc.username = root
jdbc.password01 = root

2、创建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>
</configuration>

3、创建Spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 包扫描 -->
    <context:component-scan base-package="com.itbaizhan"></context:component-scan>
    <!-- 读取配置文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!-- 创建druid数据源对象 -->
    <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>
    </bean>
    <!-- Spring创建封装过的SqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

 Spring整合MyBatis_准备数据库和实体类

准备数据库

CREATE DATABASE `student`;
USE `student`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `sex` varchar(10) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT
CHARSET=utf8;
insert  into
`student`(`id`,`name`,`sex`,`address`)
values (1,'程序员','男','北京'),(2,'北京学堂','女','北京');

准备实体类

public class Student {
    private int id;
    private String name;
    private String sex;
    private String address;
    
    // 省略构造方法/getter/setter/tostring
}

Spring整合MyBatis_编写持久层接口和service类

编写持久层接口

@Repository
public interface StudentDao {
    // 查询所有学生
    @Select("select * from student")
    List<Student> findAll();
    // 添加学生
    @Insert("insert into student values(null,#{name},#{sex},#{address})")
    void add(Student student);
}

编写service类

@Service
public class StudentService {
    // SqlSession对象
    @Autowired
    private SqlSessionTemplate sqlSession;
    // 使用SqlSession获取代理对象
    public List<Student> findAllStudent(){
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        return studentDao.findAll();
   }
}

Spring整合MyBatis_Spring整合Junit进行单元测试

之前进行单元测试时都需要手动创建Spring容器,能否在测试时让 Spring自动创建容器呢?

1 、引入Junit和Spring整合Junit依赖

<!-- junit,如果Spring5整合junit,则junit版本
至少在4.12以上 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!-- spring整合测试模块 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.3.13</version>
</dependency>

2 、编写测试类

// JUnit使用Spring方式运行代码,即自动创建spring容器。
@RunWith(SpringJUnit4ClassRunner.class)
// 告知创建spring容器时读取哪个配置类或配置文件
// 配置类写法:
@ContextConfiguration(classes=配置类.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class StudentServiceTest {
    @Autowired
    private StudentService studentService;
    
    @Test
    public void testFindAll(){
        List<Student> allStudent = studentService.findAllStudent();
        allStudent.forEach(System.out::println);
   }
}

注:使用SqlSessionTemplate创建代理对象还是需要注册接口 或者映射文件的。

1、在MyBatis配置文件注册接口

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

2、创建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整合MyBatis_自动创建代理对象 

Spring提供了MapperScannerConfigurer对象,该对象可以自动扫 描包创建代理对象,并将代理对象放入容器中,此时不需要使用 SqlSession手动创建代理对象。

1、创建MapperScannerConfigurer对象

<!-- 该对象可以自动扫描持久层接口,并为接口创建代理对象 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 配置扫描的接口包 -->
    <property name="basePackage" value="com.itbaizhan.dao"></property>
</bean>

2、Service类直接使用代理对象即可

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

3、测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath :applicationContext.xml")
public class StudentServiceTest {
    @Autowired
    private StudentService studentService;
    
    @Test
    public void testAdd(){
        Student student = new Student(0, "百战不败", "男", "上海");
        studentService.addStudent(student);
   }
}

SpringAOP_AOP简介 

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

作用:在不修改源码的基础上,对已有方法进行增强。

实现原理:动态代理技术。

优势:减少重复代码、提高开发效率、维护方便

应用场景:事务处理、日志管理、权限控制、异常处理等方面。

 SpringAOP_AOP相关术语

 为了更好地理解AOP,就需要对AOP的相关术语有一些了解

 SpringAOP_AOP入门

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

接下来我们写一个AOP入门案例:dao层的每个方法结束后都可以 打印一条日志:

1、引入依赖

<!-- spring -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.13</version>
</dependency>

<!-- AspectJ -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
</dependency>

<!-- junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

2、编写连接点

@Repository
public class UserDao {
    public void add(){
        System.out.println("用户新增");
   }
    public void delete(){
        System.out.println("用户删除");
   }
    public void update(){
        System.out.println("用户修改");
   }
}

3、编写通知类

public class MyAspectJAdvice {
    // 后置通知
    public void myAfterReturning() {
        System.out.println("打印日志...");
   }
}

4、配置切面

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:aop="http://www.springframework.org/schema/aop"
      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
        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 base-package="com.itbaizhan"></context:component-scan>
    <!-- 通知对象 -->
    <bean id="myAspectJAdvice" class="com.itbaizhan.advice.MyAspectAdvice"></bean>
    <!-- 配置AOP -->
    <aop:config>
    <!-- 配置切面 -->
        <aop:aspect ref="myAspectJAdvice">
            <!-- 配置切点 -->
            <aop:pointcut id="myPointcut" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/>
            <!-- 配置通知 -->
            <aop:after-returning method="myAfterReturning" pointcutref="myPointcut"/>
        </aop:aspect>
    </aop:config>
</beans>

5、测试

public class UserDaoTest {
    @Test
    public void testAdd(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        UserDao userDao = (UserDao) ac.getBean("userDao");
        userDao.add();
   }
    @Test
    public void testDelete(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        UserDao userDao = (UserDao)ac.getBean("userDao");
        userDao.delete();
   }
    @Test
    public void testUpdate(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        UserDao userDao = (UserDao) ac.getBean("userDao");
        userDao.update();
   }
}

 SpringAOP_通知类型

 AOP有以下几种常用的通知类型:

 1、编写通知方法

// 通知类
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 ex) {
        System.out.println("异常通知...");
        System.err.println(ex.getMessage());
   }
    // 最终通知
    public void myAfter() {
        System.out.println("最终通知");
   }
    // 环绕通知
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕前");
        Object obj = proceedingJoinPoint.proceed(); // 执行方法
        System.out.println("环绕后");
        return obj;
   }
}

2、配置切面

<!-- 配置AOP -->
<aop:config>
    <!-- 配置切面 -->
    <aop:aspect ref="myAspectJAdvice">
        <!-- 配置切点 -->
        <aop:pointcut id="myPointcut" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/>
        <!-- 前置通知 -->
        <aop:before method="myBefore" pointcut-ref="myPointcut"></aop:before>
        <!-- 后置通知 -->
        <aop:after-returning method="myAfterReturning" pointcutref="myPointcut"/>
        <!-- 异常通知 -->
        <aop:after-throwing method="myAfterThrowing" pointcutref="myPointcut" throwing="ex"/>
        <!-- 最终通知 -->
        <aop:after method="myAfter" pointcut-ref="myPointcut"></aop:after>
        <!-- 环绕通知 -->
        <aop:around method="myAround" pointcut-ref="myPointcut"></aop:around>
    </aop:aspect>
</aop:config>

SpringAOP_切点表达式 

使用AspectJ需要使用切点表达式配置切点位置,写法如下:

1、标准写法:访问修饰符 返回值 包名.类名.方法名(参数列表)

2、访问修饰符可以省略。

3、返回值使用 * 代表任意类型。

4、包名使用 * 表示任意包,多级包结构要写多个 * ,使用 *.. 表示任 意包结构

5、类名和方法名都可以用 * 实现通配。

6、参数列表

基本数据类型直接写类型
引用类型写 包名.类名
* 表示匹配一个任意类型参数
.. 表示匹配任意类型任意个数的参数

7、全通配: * *..*.*(..)

SpringAOP_多切面配置 

 我们可以为切点配置多个通知,形成多切面,比如希望dao层的每 个方法结束后都可以打印日志并发送邮件:

1、编写发送邮件的通知:

public class MyAspectJAdvice2 {
    // 后置通知
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.println("发送邮件");
   }
}

2、配置切面:

<!-- 通知对象 -->
<bean id="myAspectJAdvice" class="com.itbaizhan.advice.MyAspectAdvice"></bean>
<bean id="myAspectJAdvice2" class="com.itbaizhan.advice.MyAspectAdvice2"></bean>
<!-- 配置AOP -->
<aop:config>
    <!-- 配置切面 -->
    <aop:aspect ref="myAspectJAdvice">
        <!-- 配置切点 -->
        <aop:pointcut id="myPointcut" expression="execution(* *..*.*(..))"/>
        <!-- 后置通知 -->
        <aop:after-returning method="myAfterReturning" pointcutref="myPointcut"/>
    </aop:aspect>
    
    <aop:aspect ref="myAspectJAdvice2">
        <aop:pointcut id="myPointcut2" expression="execution(*com.itbaizhan.dao.UserDao.*(..))"/>
        <aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut2"/>
    </aop:aspect>
</aop:config>

 SpringAOP_注解配置AOP

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

1、在xml中开启AOP注解支持

<!-- 开启注解配置Aop -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

2、在通知类上方加入注解 @Aspect

3、在通知方法上方加入注解

@Before/@AfterReturning/@AfterThrowing/@After/@Around
@Aspect
@Component
public class MyAspectAdvice {
    // 后置通知
    @AfterReturning("execution(* com.itbaizhan.dao.UserDao.*(..))")
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.println("切点方法名:" + joinPoint.getSignature().getName());
        System.out.println("目标对象:" + joinPoint.getTarget());
        System.out.println("打印日志" + joinPoint.getSignature().getName() + "方法被执行了!");
   }
    // 前置通知
    @Before("execution(* com.itbaizhan.dao.UserDao.*(..))")
    public void myBefore() {
        System.out.println("前置通知...");
   }
    // 异常通知
    @AfterThrowing(value = "execution(* com.itbaizhan.dao.UserDao.*(..))",throwing = "ex")
    public void myAfterThrowing(Exception ex) {
        System.out.println("异常通知...");
        System.err.println(ex.getMessage());
   }
    // 最终通知
    @After("execution(* com.itbaizhan.dao.UserDao.*(..))")
    public void myAfter() {
        System.out.println("最终通知");
   }
    // 环绕通知
    @Around("execution(* com.itbaizhan.dao.UserDao.*(..))")
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕前");
        Object obj = proceedingJoinPoint.proceed(); // 执行方法
        System.out.println("环绕后");
        return obj;
   }
}

 4、测试:

@Test
public void testAdd2(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
    UserDao userDao = (UserDao) ac.getBean("userDao");
    userDao.update();
}

如何为一个类下的所有方法统一配置切点:

1、在通知类中添加方法配置切点

@Pointcut("execution(* com.itbaizhan.dao.UserDao.*(..))")
public void pointCut(){}

2、在通知方法上使用定义好的切点

@Before("pointCut()")
public void myBefore(JoinPoint joinPoint) {
    System.out.println("前置通知...");
}
@AfterReturning("pointCut()")
public void myAfterReturning(JoinPoint joinPoint) {
    System.out.println("后置通知...");
}

配置类如何代替xml中AOP注解支持?

在配置类上方添加@EnableAspectJAutoProxy即可

@Configuration
@ComponentScan("com.itbaizhan")
@EnableAspectJAutoProxy
public class SpringConfig {
}

SpringAOP_原生Spring实现AOP

 除了AspectJ,Spring支持原生方式实现AOP。

1、引入依赖

<!-- AOP -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.13</version>
</dependency>

2、编写通知类

// Spring原生Aop的通知类
public class SpringAop implements MethodBeforeAdvice, AfterReturningAdvice,
ThrowsAdvice, MethodInterceptor {
    /**
     * 前置通知
     * @param method 目标方法
     * @param args 目标方法的参数列表
     * @param target 目标对象
     * @throws Throwable
     */
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("前置通知");
     }
    /**
     * 后置通知
     * @param returnValue 目标方法的返回值
     * @param method 目标方法
     * @param args 目标方法的参数列表
     * @param target 目标对象
     * @throws Throwable
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置通知");
   }
    /**
     * 环绕通知
     * @param invocation 目标方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("环绕前");
        Object proceed = invocation.proceed();
        System.out.println("环绕后");
        return proceed;
   }
    /**
     * 异常通知
     * @param ex 异常对象
     */
    public void afterThrowing(Exception ex){
        System.out.println("发生异常了!");
    }
}

Spring原生方式实现AOP时,只支持四种通知类型:

 

3、编写配置类

<!-- 通知对象 -->
<bean id="springAop" class="com.itbaizhan.advice.SpringAop"></bean>
<!-- 配置代理对象 -->
<bean id="userDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <!-- 配置目标对象 -->
    <property name="target" ref="userDao"></property>
    <!-- 配置通知 -->
    <property name="interceptorNames">
        <list>
            <value>springAop</value>
        </list>
    </property>
    <!-- 代理对象的生成方式 true:使用CGLib false:使用原生JDK生成-->
    <property name="proxyTargetClass" value="true"></property>
</bean>

4、编写测试类

public class UserDaoTest2 {
    @Test
    public void testAdd(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean2.xml");
        UserDao userDao = (UserDao) ac.getBean("userDaoProxy"); // 获取的是代理对象
        userDao.update();
   }
}

SpringAOP_SchemaBased实现AOP 

SchemaBased(基础模式)配置方式是指使用Spring原生方式定义通 知,而使用AspectJ框架配置切面。

1、编写通知类

public class SpringAop implements MethodBeforeAdvice, AfterReturningAdvice,ThrowsAdvice, MethodInterceptor {
    /**
     * 前置通知
     * @param method 目标方法
     * @param args 目标方法的参数列表
     * @param target 目标对象
     * @throws Throwable
     */
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("前置通知");
     }
    /**
     * 后置通知
     * @param returnValue 目标方法的返回值
     * @param method 目标方法
     * @param args 目标方法的参数列表
     * @param target 目标对象
     * @throws Throwable
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置通知");
   }
    /**
     * 环绕通知
     * @param invocation 目标方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("环绕前");
        Object proceed = invocation.proceed();
        System.out.println("环绕后");
        return proceed;
   }
    /**
     * 异常通知
     * @param ex 异常对象
     */
    public void afterThrowing(Exception ex){
        System.out.println("发生异常了!");
   }
}

2、配置切面

<!-- 通知对象 -->
<bean id="springAop2" class="com.itbaizhan.aop.SpringAop2"/>
<!-- 配置切面 -->
<aop:config>
    <!-- 配置切点-->
    <aop:pointcut id="myPointcut" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/>
    <!-- 配置切面:advice-ref:通知对象 pointcut-ref:切点 -->
    <aop:advisor advice-ref="springAop2" pointcut-ref="myPointcut"/>
</aop:config>

3、测试

@Test
public void t6(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("aop3.xml");
    UserDao userDao = (UserDao) ac.getBean("userDao");
    userDao.add();
}

Spring事务_事务简介

 

 事务:不可分割的原子操作。即一系列的操作要么同时成功,要么同时失败。

开发过程中,事务管理一般在service层,service层中可能会操作多次数据库,这些操作是不可分割的。否则当程序报错时,可能会造 成数据异常。

如:张三给李四转账时,需要两次操作数据库:张三存款减少、李四存款增加。如果这两次数据库操作间出现异常,则会造成数据错 误。

1、准备数据库

CREATE DATABASE `spring` ;
USE `spring`;
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `balance` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT
CHARSET=utf8;
insert  into `account`(`id`,`username`,`balance`) values (1,'张三',1000),(2,'李四',1000);

2、创建maven项目,引入依赖

<dependencies>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
   <!-- mysql驱动包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connectorjava</artifactId>
        <version>8.0.26</version>
    </dependency>
    <!-- druid连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.8</version>
    </dependency>
    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>springcontext</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>springjdbc</artifactId>
        <version>5.3.13</version>
    </dependency>
    <!-- MyBatis与Spring的整合包,该包可以让Spring创建MyBatis的对象 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatisspring</artifactId>
        <version>2.0.6</version>
    </dependency>
    <!-- junit,如果Spring5整合junit,则junit版本至少在4.12以上 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- spring整合测试模块 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>springtest</artifactId>
        <version>5.3.13</version>
        <scope>test</scope>
    </dependency>
</dependencies>

3、创建配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 包扫描 -->
    <context:component-scan basepackage="com.itbaizhan"></context:component-scan>
    <!-- 创建druid数据源对象 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itbaizhan.dao"></property>
    </bean>
</beans>

4、编写Java代码

// 账户
public class Account {
    private int id; // 账号
    private String username; // 用户名
    private double balance; // 余额
    
    // 省略getter/setter/tostring/构造方法
}

@Repository
public interface AccountDao {
    // 根据id查找用户
    @Select("select * from account where id = #{id}")
    Account findById(int id);
    // 修改用户
    @Update("update account set balance = #{balance} where id = #{id}")
    void update(Account account);
}

@Service
public class AccountService {
    @Autowired
    private AccountDao accountDao;
    /**
     * 转账
     * @param id1 转出人id
     * @param id2 转入人id
     * @param price 金额
     */
    public void transfer(int id1, int id2, double price) {
        // 转出人减少余额
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance()-price);
        accountDao.update(account1);
        int i = 1/0; // 模拟程序出错
        // 转入人增加余额
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance()+price);
        accountDao.update(account2);
   }
}

5、测试转账

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath :applicationContext.xml")
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;
    @Test
    public void testTransfer(){
        accountService.transfer(1,2,500);
   }
}

此时没有事务管理,会造成张三的余额减少,而李四的余额并没有 增加。所以事务处理位于业务层,即一个service方法是不能分割的。

Spring事务_Spring事务管理方案 

 在service层手动添加事务可以解决该问题:

@Autowired
private SqlSessionTemplate sqlSession;
public void transfer(int id1, int id2,double price) {
    try{
        // account1修改余额
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance()- price);
        accountDao.update(account1);
        int i = 1/0; // 模拟转账出错
        // account2修改余额
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance()+price);
        accountDao.update(account2);  
        sqlSession.commit();
     }catch(Exception ex){
        sqlSession.rollback();
   }
}

但在Spring管理下不允许手动提交和回滚事务。此时我们需要使用 Spring的事务管理方案,在Spring框架中提供了两种事务管理方案:

1 编程式事务:通过编写代码实现事务管理。

2 声明式事务:基于AOP技术实现事务管理。

在Spring框架中,编程式事务管理很少使用,我们对声明式事务管 理进行详细学习。 Spring的声明式事务管理在底层采用了AOP技术,其最大的优点在 于无需通过编程的方式管理事务,只需要在配置文件中进行相关的 规则声明,就可以将事务规则应用到业务逻辑中。 

 使用AOP技术为service方法添加如下通知:

 Spring事务_Spring事务管理器

 Spring依赖事务管理器进行事务管理,事务管理器即一个通知类, 我们为该通知类设置切点为service层方法即可完成事务自动管理。 由于不同技术操作数据库,进行事务操作的方法不同。如:JDBC提 交事务是 connection.commit() ,MyBatis提交事务是 sqlSession.commit() ,所以 Spring提供了多个事务管理器。

 我们使用MyBatis操作数据库,接下来使用 DataSourceTransactionManager 进行事务管理。

 1、引入依赖

<!-- 事务管理 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.3.13</version>
</dependency>
<!-- AspectJ -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
</dependency>

2、在配置文件中引入约束

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

3、进行事务配置

<!-- 事务管理器 -->
<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="*"/>
    </tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
    <!-- 配置切点 -->
    <aop:pointcut id="pointcut" expression="execution(* com.itbaizhan.service.*.*(..))"/>
    <!-- 配置通知 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
</aop:config>

Spring事务_事务控制的API

 Spring进行事务控制的功能是由三个接口提供的,这三个接口是 Spring实现的,在开发中我们很少使用到,只需要了解他们的作用 即可:

PlatformTransactionManager接口

PlatformTransactionManager是Spring提供的事务管理器接口,所 有事务管理器都实现了该接口。该接口中提供了三个事务操作方法:

1、TransactionStatus getTransaction(TransactionDefinition definition):获取事务状态信息。

2、void commit(TransactionStatus status):事务提交

3、void rollback(TransactionStatus status):事务回滚

 TransactionDefinition接口

TransactionDefinition是事务的定义信息对象,它有如下方法:

String getName():获取事务对象名称。

int getIsolationLevel():获取事务的隔离级别。

int getPropagationBehavior():获取事务的传播行为。

int getTimeout():获取事务的超时时间。

boolean isReadOnly():获取事务是否只读。

TransactionStatus接口 

TransactionStatus是事务的状态接口,它描述了某一时间点上事务 的状态信息。它有如下方法:

void flush() 刷新事务

boolean hasSavepoint() 获取是否存在保存点

boolean isCompleted() 获取事务是否完成

boolean isNewTransaction() 获取是否是新事务

boolean isRollbackOnly() 获取是否回滚

void setRollbackOnly() 设置事务回滚

Spring事务_事务的相关配置 

<tx:advice> 中可以进行事务的相关配置:

<tx:advice id="txAdvice">
    <tx:attributes>
        <tx:method name="*"/>
        <tx:method name="find*" readonly="true"/>
    </tx:attributes>
</tx:advice>

 Spring事务_事务的传播行为

 事务传播行为是指多个含有事务的方法相互调用时,事务如何在这 些方法间传播。 如果在service层的方法中调用了其他的service方法,假设每次执行 service方法都要开启事务,此时就无法保证外层方法和内层方法处 于同一个事务当中。

// method1的所有方法在同一个事务中
public void method1(){
    // 此时会开启一个新事务,这就无法保证method1()中所有的代码是在同一个事务中
    method2();
    System.out.println("method1");
}
public void method2(){
    System.out.println("method2");
}

事务的传播特性就是解决这个问题的,Spring帮助我们将外层方法 和内层方法放入同一事务中。

 

Spring事务_事务的隔离级别 

 事务隔离级别反映事务提交并发访问时的处理态度,隔离级别越 高,数据出问题的可能性越低,但效率也会越低。

 Spring事务_注解配置声明式事务

Spring支持使用注解配置声明式事务。用法如下:

1、注册事务注解驱动

<!-- 注册事务注解驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

2、在需要事务支持的方法或类上加@Transactional

 @Service
// 作用于类上时,该类的所有public方法将都具有该类型的事务属性
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class AccountService {
    @Autowired
    private AccountDao accountDao;
    /**
     * 转账
     * @param id1 转出人id
     * @param id2 转入人id
     * @param price 金额
     */
    // 作用于方法上时,该方法将都具有该类型的事务属性
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    public void transfer(int id1, int id2,double price) {
        // account1修改余额
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance()-price);
        accountDao.update(account1);
        int i = 1/0; // 模拟转账出错
        // account2修改余额
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance()+price);
        accountDao.update(account2);
   }
}

3 配置类代替xml中的注解事务支持:在配置类上方写 @EnableTranscationManagement

@Configuration
@ComponentScan("com.itbaizhan")
@EnableTransactionManagement
public class SpringConfig {
    @Bean
    public DataSource getDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
       druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
       druidDataSource.setUrl("jdbc:mysql:///spring");
       druidDataSource.setUsername("root");
       druidDataSource.setPassword("root");
        return druidDataSource;
}
    @Bean
    public SqlSessionFactoryBean getSqlSession(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
   }
    @Bean
    public MapperScannerConfigurer getMapperScanner(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.itbaizhan.dao");
        return mapperScannerConfigurer;
   }
    @Bean
    public DataSourceTransactionManager getTransactionManager(DataSource dataSource){
         DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
      dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
   }
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/46038.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

少儿编程 电子学会图形化编程等级考试Scratch一级真题解析(判断题)2022年9月

2022年9月scratch编程等级考试一级真题 判断题(共10题,每题2分,共20分) 26、一个角色只能包含一个造型 答案:错 考点分析:考查角色造型,一个角色可以有多个造型,所以错误 27、我们可以根据需要将角色的任意一点设为造型中心 答案:对 考点分析:考查角色造型,角色…

CC1310F128RSMR Sub-1GHz射频微控制器 - MCU 433MHz 868MHz 915MHz ULP Wireless MCU

CC1310F128RSMR Sub-1GHz射频微控制器 - MCU 433MHz 868MHz 915MHz ULP Wireless MCU CC1310设备是德州仪器公司生产的一款性价比高、超低功耗、Sub-1GHz射频设备,这是SimpleLink的一部分,微控制器&#xff08;MCU&#xff09;平台。该平台包括Wi-Fi&#xff0c;蓝牙低能耗&am…

世界杯中隐藏的IoT物联网黑科技

世界杯首个大冷门上演&#xff01;&#xff01;夺冠热门阿根廷竟然一比二输给了沙特队&#xff0c;实在让人始料未及&#xff0c;让不少球迷都在黯然神伤。 回过头看&#xff0c;上半场4粒进球&#xff0c;被判越位无效的有3粒。整场比赛累计7次越位判罚&#xff0c;超过了上届…

APS智能排产系统的优势

APS智能排产系统是通过同步考虑多种有限能力资源的约束&#xff0c;依据各种预设规则&#xff0c;针对解决&#xff1a;客户订单交期评估与答复、人工排产效率低、设备资源利用率低、物料计划与生产计划脱节、生产计划执行率低、库存积压与生产缺料等相关问题&#xff0c;依靠严…

WebRTC技术专题(2)【大势所趋,迈向认识 WebRTC 的第一步】

每日一句 人生的挑战&#xff0c;无处不在&#xff0c;满怀信心&#xff0c;轻装上路&#xff0c;明天永远是充满希望的战场。 承接上文 承接上文的内容介绍完相关WebRTC技术的概念和发展历程后&#xff0c;开始初步摸索一下相关WebRTC技术的功能和原理。 技术回顾 WebRTC概念…

字符串压缩(二)之LZ4

一、LZ4压缩与解压 LZ4有两个压缩函数。默认压缩函数原型&#xff1a; int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity); 快速压缩函数原型&#xff1a; int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapaci…

router路由的配置和使用(详细教程)

vue路由的原理&#xff1a; 路由就是专门来实现单页面应用的&#xff1b;根据不同的路径&#xff0c;加载不同的组件&#xff1b;路径和组件之间一一映射的关系&#xff1b;路径&#xff0c;组件一一对应&#xff1b;加载这个路径&#xff0c;这个组件就出来了&#xff1b;原理…

第五章. 可视化数据分析分析图表—概念介绍

第五章. 可视化数据分析分析图表 5.1 概念介绍 1.如何选择合适的图标类型 1).图标分类框架示意图&#xff1a; 2.图表的基本组成 1).图表的基本组成部分&#xff1a;画布&#xff0c;图标标题&#xff0c;绘画区&#xff0c;数据系列&#xff0c;坐标轴&#xff0c;坐标轴标题…

publish前自动执行sonarqube

根据SonarQube官方描述&#xff0c;SonarQube由三个组件组成&#xff1a; SonarQube Server&#xff0c;运行如下进程&#xff1a; 一个服务于SonarQube用户界面的web服务器基于Elasticsearch的搜索服务器负责处理代码分析报告并将其保存在SonarQube数据库中的计算引擎 Databa…

多卡聚合通信设备在广电视频传输行业解决方案

1 背景介绍 现场视频回传作为信息量最大、信息表达最直观的一种方式&#xff0c;一直是各家电视台、报社等媒体单位获取素材最理想的方式。由于受技术、成本及基础设施的限制&#xff0c;视频素材的回传的距离、质量一直受到较大影响。而随着4G/5G技术的快速发展&#xff0c;多…

【JAVA案例】判断电话号码运营商

博主&#xff1a;&#x1f44d;不许代码码上红 欢迎&#xff1a;&#x1f40b;点赞、收藏、关注、评论。 格言&#xff1a; 大鹏一日同风起&#xff0c;扶摇直上九万里。 文章目录问题提出&#xff1a;如何判断电话号码属于哪个运营商&#xff1f;一、代码设计思路二、完整源…

Java SPI机制的使用和理解

前言&#xff1a; SPI(Service Provider Interface)&#xff0c;是JDK内置的一种服务提供发现机制&#xff0c;Java中 SPI 机制主要思想是将装配的控制权移到程序之外&#xff0c;在模块化设计中这个机制尤其重要&#xff0c;其核心思想就是解耦 1、大家都知道API&#xff0c;却…

01【高内聚低耦合、Spring概述、IOC容器、Bean的配置方式】

文章目录01【高内聚低耦合、Spring概述、IOC】一、高内聚低耦合1.1 程序架构设计1.2 低耦合1.2.1 耦合概念1.2.2 如何降低耦合1.3 高内聚1.4 不能完全低耦合二、Spring概述2.1 Spring 是什么2.2 Spring出现的背景2.3 Spring包详解三、Spring快速入门3.1 搭建Spring环境3.2 编写…

60 - 数组类模板

---- 整理自狄泰软件唐佐林老师课程 1. 预备知识 模板参数可以是 数值型参数&#xff08;非类型参数&#xff09; 数值型模板参数的 限制 变量不能作为模板参数浮点数不能作为模板参数类对象不能作为模板参数 本质&#xff1a;模板参数是在 编译阶段 被处理的单元&#xff0c…

基于内部模型的鲁棒图像增强

论文题目&#xff1a; ROBUST INTERNAL EXEMPLAR-BASED IMAGE ENHANCEMENT 1 摘要 图像增强的目的是修改图像&#xff0c;以实现更好的人类视觉系统感知或更合适的表示来进一步分析。根据给定输入图像的不同属性&#xff0c;任务也会有所不同&#xff0c;如噪声去除、去模糊、…

jsp三好学生评审管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 JSP 三好学生评审管理系统 是一套完善的web设计系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql&#xff0…

R语言highfrequency高频金融数据导入

R中针对高频数据的添加包highfrequency&#xff0c;用于组织高频数据&#xff0c; 高频数据的清理、整理&#xff0c;高频数据的汇总&#xff0c;使用高频数据建立相关模型 都非常方便。但是其中数据输入的过程中&#xff0c;会使用到包里的函数convert()。 最近我们被客户要求…

软件测试行业女生真的没有一席之地了吗,还能入行软件测试吗?

可以&#xff0c;但并不容易。 要比男生面临更多的挑战和付出更多的努力。 首先我强烈反对女生更适合做测试的这种论调: ●女生更为心细&#xff0c;更有耐心&#xff0c;能够更好的找出bug;&#xff0c;测试不用写代码&#xff0c;女生学更容易上手; ●测试强度低&#xff0c;…

发送自定义广播

文章目录发送自定义广播发送标准广播发送有序广播发送自定义广播 发送标准广播 新建一个MyBroadcastReceiver,在onReceive()方法当中编写具体逻辑 class MyBroadcastReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {Toast.make…

停止员工拖延症!工时管理系统的作用之一

你能想象每天支付给每位员工的工资会损失 27% 吗&#xff1f;这就是最近一项研究发现的正在发生的事。根据 rebootonline.com 的研究&#xff0c;每位员工平均每天要花 122 分钟在拖延上。这意味着这些员工只工作了 73% 的工作日时间&#xff0c;即使他们的工时表另有说明。公司…