Spring Family Bucket of Spring

insert image description here

Spring Family Bucket

Learning official website: https://spring.io/

Chapter 1 Spring5 Framework

Spring Framework Documentation

https://docs.spring.io/spring-framework/docs/current/reference/html/index.html

1.1 Spring framework overview

/*
1、Spring是轻量级的开源的JavaEE框架
2、Spring可以解决企业应用开发的复杂性
3、Spring有两个核心部分:IOC和AOP
(1)IOC:控制反转,把创建对象过程交给Spring进行管理
(2)AOP:面向切面,不修改源代码进行功能增强
4、Spring特点
(1)方便解耦,简化开发
(2)AOP编程支持
(3)方便程序测试
(4)方便和其他框架进行整合
(5)方便进行事务操作
(6)降低API开发难度
*/

Getting Started Case

The first step is to download Spring5 and select the latest stable version—5.3.8

https://repo.spring.io/release/org/springframework/spring/
insert image description here
Step 2 Create a java project and import Spring-related JAR packages
insert image description here
Step 3 Create classes and methods

User.java

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

The fourth step is to create a Spring configuration file bean1.xml and create an object

<?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对象创建-->
    <bean id="user" class="edu.mm.User"></bean>
</beans>

Step 5 Test

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

Run the screenshot:
insert image description here

1. 2 IOC container

1.2.1 IOC concept

(1) IOC, inversion of control, hand over the object creation and calling process between objects to Spring for management.

(2) The purpose of using IOC: to reduce the degree of coupling.

1.2.2 The underlying principle of IOC

Keywords: xml parsing, factory pattern, reflection

Requirements: Create UserService.java and UserDao.java, and hope to call a method in the dao layer in the service layer.

IOC process

The first step: Create an object through the xml configuration file.

<bean id="" class=""></bean>

Step 2: Create a factory class

class UserFactory{
    
    
    public static UserDao getDao(){
    
    
        String classValue=class属性值;//1.xml解析(基于Dom4j),获取全类名
        Class clazz=Class.forName(classValue);//2.通过反射创建对象
        return (UserDao)clazz.newInstance();
    }
}

Step 3: Create objects in the service layer through the factory pattern

class UserService{
    
    
    public void excute(){
    
    
        UserDao dao=UserFactory.getDao();
        dao.add();
    }
}

Disadvantages of the original method new keyword: the degree of coupling is too high

UserDao.java

class UserDao{
    
    
    public void add(){
    
    
        ...
    }
}

UserService.java

class UserService{
    
    
    UserDao userDao=new UserDao();
    userDao.add();
}   

Factory mode The factory class is used as middleware to reduce the coupling between the service layer and the dao layer.

UserFactory.java

class UserFactory{
    
    
    public static UserDao getDao(){
    
    
        return new UserDao();
    }
}

UserService.java

class UserService{
    
    
    public void excute(){
    
    
        UserDao dao=UserFactory.getDao();
        dao.add();
    }
}

1.2.3 IOC interface (BeanFactory)

  • The idea of ​​IOC is based on the IOC container, and the bottom layer of the IOC container is the object factory

  • Spring provides two ways of IOC container (two interfaces)

    • BeanFactory

      IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用
      *加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象 
      
    • ApplicationContext

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

1.2.4 IOC operation bean management (xml-based)

IOC operation Bean management includes: Spring creates objects and injects attributes.

There are two ways of Bean management operations: xml, annotations

  • Create objects based on xml

     <bean id="user" class="edu.mm.User"></bean>
    

    【Notice】

    (1) In the spring configuration file, use the bean tag and add corresponding attributes in the tag to realize object creation

    (2) There are many attributes in the bean tag, and the commonly used attributes are as follows

    ​ id attribute: unique identifier

    ​ class attribute: class full path (package class path)

    (3) When creating an object, the default is to execute the parameterless construction method to complete the object creation

  • Inject attributes based on xml

    /*DI:依赖注入,就是注入属性*/
    
    • Injection using the set method

      Step 1: Create an entity class, define attributes and corresponding set methods

      public class User {
              
              
          public String name;
          public String stumum;
          public void setName(String name) {
              
              
              this.name = name;
          }
          public void setStumum(String stumum) {
              
              
              this.stumum = stumum;
          }
      }
      
      

      Step 2: Create an object in the spring configuration file and inject properties

       <!--使用property属性注入  name:类里面属性名称  value:向属性注入的值-->
      <bean id="user" class="edu.mm.User">
              <property name="name" value="java"></property>
              <property name="stumum" value="171404050119"></property>
      </bean>
      
    • Injection using a parameterized constructor

      Step 1: Create classes, attributes, and constructors with parameters

      public class Book {
              
              
          public String bName;
          public String author;
          public Book(String bName, String author) {
              
              
              this.bName = bName;
              this.author = author;
          }
      }
      
      

      Step 2: Configure in the spring configuration file

      <bean id="book" class="edu.mm.Book">
              <constructor-arg name="author" value="屈原"></constructor-arg>
              <constructor-arg name="bName" value="楚辞"></constructor-arg>
      </bean>
      

      Step Three: Test

       @Test
      public void testBook(){
              
              
      //1.加载spring配置文件
      ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
      //2.获取通过配置文件创建的对象
      Book book = context.getBean("book", Book.class);
      System.out.println(book.bName);
      }
      
  • Inject other types of attributes based on xml

    • Injection property - external bean

      /*
      (1)创建两个类service类和dao类
      (2)在service调用dao里面的方法
      (3)在spring配置文件中进行配置
      */
      public class UserService {
              
              
          public UserDao userDao;
          public void setUserDao(UserDao userDao) {
              
              
              this.userDao = userDao;
          }
          public void show(){
              
              
              userDao.showInfo();
              System.out.println("I am service");
          }
      }
      
      <!--注入userDao对象  name属性:类里面属性名称  ref属性:创建userDao对象bean标签id值-->
      <bean id="userService" class="edu.mm.service.UserService">
              <property name="userDao" ref="userDao"></property>
      </bean>
      <bean id="userDao" class="edu.mm.dao.UserDao"></bean>
      
    • Injection property - inner bean

      /*
      一对多关系:部门和员工
      在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示
      */
      public class Dept {
              
              
          public String dName;
      
          public void setdName(String dName) {
              
              
              this.dName = dName;
          }
      }
      
      public class Emp {
              
              
          public String empName;
          public String empGender;
          public Dept dept;//员工属于某一个部门,使用对象形式表示
          public void setEmpName(String empName) {
              
              
              this.empName = empName;
          }
          public void setEmpGender(String empGender) {
              
              
              this.empGender = empGender;
          }
          public void setDept(Dept dept) {
              
              
              this.dept = dept;
          }
      }
      
      <bean id="emp" class="edu.mm.bean.Emp">
              <property name="empName" value="李白"></property>
              <property name="empGender" value=""></property>
              <property name="dept">
                  <bean id="dept" class="edu.mm.bean.Dept">
                      <property name="dName" value="保卫科"></property>
                  </bean>
              </property>
      </bean>
      
    • Injecting properties—cascading assignments

      method one:

      <bean id="emp" class="edu.mm.bean.Emp">
           <!--设置两个普通属性-->
           <property name="empName" value="李白"></property>
           <property name="empGende" value=""></property>
           <!--级联赋值-->
           <property name="dept" ref="dept"></property>
      </bean>
      <bean id="dept" class="edu.mm.bean.Dept">
           <property name="dName" value="保卫科"></property>
      </bean>
      
      

      Method 2:

      <!--前提:Emp实体类要有getDept()-->
      <bean id="emp" class="edu.mm.dao.Emp">
              <property name="empName" value="李白"></property>
              <property name="empGender" value=""></property>
              <property name="dept" ref="dept"></property>
              <property name="dept.dName" value="保卫科"></property>
          </bean>
      <bean id="dept" class="edu.mm.dao.Dept"></bean>
      
    • Inject Attributes—Collection Attributes

      1. Inject array type attributes

      2. Inject the List collection type property

      3. List collection injection object properties

      4. Inject the Map collection type attribute

      5. Inject the Set collection type attribute

      public class Stu {
              
              
       //1 数组类型属性
       private String[] courses;
       //2 List集合类型属性
       private List<String> list;
       //3 List集合注入对象属性
       private List<Course> courseList;
       //4 Map 集合类型属性
       private Map<String,String> maps;
       //5 Set 集合类型属性
       private Set<String> sets;
      
       public void setSets(Set<String> sets) {
              
              
       this.sets = sets;
       }
       public void setCourses(String[] courses) {
              
              
       this.courses = courses;
       }
       public void setList(List<String> list) {
              
              
       this.list = list;
       }
       public void courseList(List<Course> courseList) {
              
              
       this.courseList = courseList;
       }  
       public void setMaps(Map<String, String> maps) {
              
              
       this.maps = maps;
       }
      }
      
      <!--集合类型属性注入-->
      <bean id="stu" class="edu.mm.bean.Stu">
           <!--1.数组类型属性注入-->
           <property name="courses">
              <array>
                  <value>java 课程</value>
                  <value>数据库课程</value>
              </array>
           </property>
           <!--2.list类型属性注入-->
           <property name="list">
              <list>
                 <value>张三</value>
                 <value>小三</value>
              </list>
           </property>
          <!--3.List集合中注入对象属性-->
          <property name="courseList">
             <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
             </list>
          </property>
           <!--4.map类型属性注入-->
           <property name="maps">
              <map>
                 <entry key="JAVA" value="java"></entry>
                 <entry key="PHP" value="php"></entry>
              </map>
           </property>
           <!--5.set类型属性注入-->
           <property name="sets">
              <set>
                 <value>MySQL</value>
                 <value>Redis</value>
              </set>
           </property>
      </bean>
      <bean id="course1" class="edu.mm.bean.Course">
       <property name="cname" value="Spring5 框架"></property>
      </bean>
      <bean id="course2" class="edu.mm.bean.Course">
       <property name="cname" value="MyBatis 框架"></property>
      </bean>
      
  • FactoryBean

    1. Spring has two types of beans, one ordinary bean and the other factory bean (FactoryBean)

    2. Ordinary bean: the bean type defined in the configuration file is the return type

    3. Factory bean: the bean type defined in the configuration file can be different from the return type

    ​ The first step is to create a class, let this class be a factory bean, and implement the interface FactoryBean

    The second step is to implement the method in the interface, and define the returned bean type in the implemented method

  • IOC operation bean management (bean scope)

    /*
    在Spring中,默认情况下,bean 是单实例对象
    
    (1)在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
    (2)scope 属性值
               第一个值 默认值,singleton,表示是单实例对象
               第二个值 prototype,表示是多实例对象
    (3)singleton 和 prototype 区别
        第一,singleton单实例,prototype多实例
        第二,scope=singleton,加载spring配置文件时创建单实例对象
             scope=prototype,在调用getBean方法时创建多实例对象
    */
    
  • IOC Operation Bean Management (bean lifecycle)

    /*bean 生命周期:
    (1)通过构造器创建 bean 实例(无参数构造)
    (2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
    (3)调用 bean 的初始化的方法(需要进行配置初始化的方法)
    (4)使用bean(对象获取到了)
    (5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)
    */
    
  • IOC operation bean management (xml autowiring)

    According to the specified assembly rules (property name or property type), Spring automatically injects the matching property value

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

1.2.5 IOC operation bean management (annotation-based)

  • The meaning of the annotation

    (1) Annotation is a special code mark, format: @annotation name (attribute name=attribute value, attribute name=attribute value...)

    (2) Use annotations, which act on classes, methods, and attributes

    (3) Purpose of using annotations: Simplify xml configuration

  • Spring provides the following annotations for object creation in Bean management

    (1)@Component

    (2)@Service

    (3)@Controller

    (4)@Repository

    The functions of the above four annotations are the same, and they can all be used to create bean instances

  • Annotation-based object creation

    • Step 1: Introduce dependency spring-aop-5.3.8.jar

    • Step 2: Turn on component scanning

       <!--开启组件扫描 1、如果扫描多个包,多个包使用逗号隔开 ;2、扫描包上层目录-->
      <context:component-scan base-package="edu.mm"></context:component-scan>
      
    • Step 3: Create a class and add object creation annotations on the class

      /*在注解里面value属性值可以省略不写,默认值是类名称,首字母小写*/
      
  • Annotation-based property injection

    • @Autowired: Autowire based on attribute type

    • @Resource: By default, it can be injected by type, or it can be injected by name

    • @Value: Inject normal type properties

    • @Qualifier: inject by name

      Use @Qualifier with @Autowired

  • Fully Annotated Development

    Step 1: Create a configuration class to replace the xml configuration file

    @Configuration
    @ComponentScan(basePackages = "edu.mm")
    public class SpringConfig {
          
          
    ....
    }
    

    Step 2: Write the test class

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

1.3 AOP

1.3.1 AOP concept

Aspect-oriented programming (aspect), using AOP can isolate each part of the business logic, so that the coupling degree between the parts of the business logic is reduced, the reusability of the program is improved, and the efficiency of development is improved. In short, It is to add new functions to the main functions without modifying the source code.

1.3.2 The underlying principle of AOP

The underlying layer of AOP is implemented using dynamic proxies, including: JDK dynamic proxies and CGLIB dynamic proxies.

  • JDK dynamic proxy - with interface
/*创建接口实现类代理对象,增强类的方法*/
  • CGLIB dynamic proxy - no interface

    /*创建子类的代理对象,增强类的方法*/
    

1.4 JdbcTemplate

The Spring framework encapsulates JDBC and uses JdbcTemplate to facilitate database operations.

step:

Step 1 : Preparations

(1) Introduce related jar packages

  • druid-1.1.9.jar

  • mysql-connector-java-5.1.7-bin.jar

  • spring-jdbc-5.3.8.jar

  • spring-orm-5.3.8.jar

  • spring-tx-5.3.8.jar

(2) Create a database

/*
Navicat MySQL Data Transfer

Source Server         : hh
Source Server Version : 80023
Source Host           : localhost:3306
Source Database       : school

Target Server Type    : MYSQL
Target Server Version : 80023
File Encoding         : 65001

Date: 2021-07-05 11:59:40
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sno` char(10) NOT NULL,
  `sname` char(20) DEFAULT NULL,
  `ssex` char(2) DEFAULT NULL,
  `sage` smallint DEFAULT NULL,
  `sdept` char(20) DEFAULT NULL,
  PRIMARY KEY (`sno`),
  UNIQUE KEY `sname` (`sname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('100256', '刘晨', '男', '19', 'IS');
INSERT INTO `student` VALUES ('1114', '马修', '男', '20', 'CS');
INSERT INTO `student` VALUES ('171145', '屈明明', '男', '15', 'CS');
INSERT INTO `student` VALUES ('1714', '李白', '男', '100', '九三学社');
INSERT INTO `student` VALUES ('178963', '张力', '女', '18', 'MA');

(3) Configure the database connection pool in the spring configuration file

Method 1: Directly configure the database connection pool

     <!--组件扫描-->
    <context:component-scan base-package="edu.mm"></context:component-scan>
    <!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="jdbc:mysql:///school?useUnicode=true&characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>

Method 2: spring.xml reads the dbConfig.properties file to configure the database connection pool

dbConfig.properties

jdbc.user=root
jdbc.password=123456
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8
jdbc.driverClass=com.mysql.jdbc.Driver

spring.xml

    <!--引入外部配置文件-->
    <context:property-placeholder location="classpath:dbConfig.properties">                   </context:property-placeholder>
    <!--组件扫描-->
    <context:component-scan base-package="edu.mm"></context:component-scan>
    <!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.jdbcUrl}"></property>
        <property name="username" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
    </bean>

(4) Configure the JdbcTemplate object and inject DataSource

    <!--创建JdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

Step 2 : Write code and use JdbcTemplate to operate the database

Call update (), queryForObject () in the JdbcTemplate object to realize the operation of adding, deleting, modifying and checking

Take inserting a piece of data as an example:

@Test
    public void test1(){
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        //1.创建sql语句
        String sql="insert into student values(?,?,?,?,?)";
        Student student=new Student();
        student.setSno("1714");
        student.setSname("李白");
        student.setSage(100);
        student.setSsex("男");
        student.setSdept("九三学社");
        //2.调用方法实现
        Object[] args={
    
    student.getSno(),student.getSname(),student.getSsex(),student.getSage(),student.getSdept()};
        int ret = jdbcTemplate.update(sql, args);
        System.out.println(ret);
    }

insert image description here
Replenish:

/*
param1:sql语句
param2:可变参数,sql语句的值
*/
int update(String sql, @Nullable Object... args);

/*添加一条数据*/
String sql = "insert into t_book values(?,?,?)";
Object[] args = {
    
    book.getUserId(), book.getUsername(), book.getUstatus()};
/*修改一条数据*/
String sql = "update t_book set username=?,ustatus=? where user_id=?";
Object[] args = {
    
    book.getUsername(), book.getUstatus(),book.getUserId()};
/* 删除一条数据*/
String sql = "delete from t_book where user_id=?";


/*
param1:sql语句
param:返回类型Class
*/
String sql = "select count(*) from t_book";//查询表的记录数
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);//查询返回某个值


/*
param1:sql 语句
param2:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
param3:sql语句值
*/
String sql = "select * from t_book where user_id=?";//查询返回对象
Book book = jdbcTemplate.queryForObject(sql, new 
BeanPropertyRowMapper<Book>(Book.class), id);//查询返回对象


/*
param1:sql 语句
param2:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
*/
String sql = "select * from t_book";//查询返回集合
List<Book> bookList = jdbcTemplate.query(sql, new 
BeanPropertyRowMapper<Book>(Book.class));//查询返回集合

Step 3: Solve the bug
insert image description here
When you use @Autowired automatic injection in the test class, the above error will be reported

Solution: Add @RunWith(SpringRunner.class)annotations above the test class

Reason: With @RunWith(SpringRunner.class), these classes can be instantiated into the spring container, and automatic injection can take effect, otherwise a NullPointerExecption

1.5 Transaction Management

A transaction is the most basic unit of database operations. Logically, a set of operations either succeeds, or all operations fail if one fails.

When performing transaction management in Spring, use declarative transaction management, the most commonly used method is based on annotations, use @Transactiona annotation to add things to the Service layer, the bottom layer is based on AOP, and perform transaction management through the PlatformTransactionManager interface.

Four characteristics of things: atomicity, consistency, isolation, and persistence

Typical scenario: bank transfer

1.6 New features of Spring5

(1) Integrated log framework

(2) @Nullable annotation

(3) Functional registration object

(4) Integrate the JUnit5 unit testing framework

(5) Use of Spring Webflux

Guess you like

Origin blog.csdn.net/weixin_44490884/article/details/118486747