全网最详细的Spring入门教程

全网最详细的Spring入门教程

目录

全网最详细的Spring入门教程

一.Spring的来源

1.耦合代码如下:

2.解耦合代码如下:

二.Spring的本质

基本概念:

三.Spring的使用

1.无Spring注解具体实现步骤:

1.1.大致步骤:

创建 接口1 类1 接口2 类2

写 bean文件

写bean的配置

获取类

1.2.有简单类型依赖和无依赖的类实现方式如下:

项目框架:

pom.xml

ApplicationContext.xml

测试类(需要被容器创建的类)

客户类(使用者):

运行结果:

1.3.有集合类型依赖的类实现方式如下:

项目框架:

pom.xml

ApplicationContext.xml

测试类(需要被容器创建的类)

客户类(使用者):

运行结果:

1.4.有引用类型依赖的类实现方式如下:

项目框架:

pom.xml

ApplicationContext.xml

测试类(需要被容器创建的类)

客户类(使用者):

运行结果:

2.Spring注解具体实现步骤:

plus:Spring中的常用注解

2.1.大致步骤:

创建 接口1 类1 接口2 类2

在需要new的类加上注解

写 bean文件

写bean的配置 : 扫描命令代码

获取类

2.2.1有简单类型依赖和无依赖的类实现方式如下:

项目框架:

pom.xml

ApplicationContext.xml

测试类(需要被容器创建的类)

客户类(使用者)

运行结果:

2.2.2有简单类型依赖和无依赖的类实现方式如下:优化版:

项目框架:

pom.xml

SpringBeanConfiguration类的配置:

测试类(需要被容器创建的类)

客户类(使用者)

运行结果:

2.3.有集合类型依赖的类实现方式如下:

项目框架:

pom.xml

SpringBeanConfiguration类的配置:

测试类(需要被容器创建的类)

客户类(使用者)

运行结果:

2.4.有引用类型依赖的类实现方式如下:

项目框架:

pom.xml

SpringBeanConfiguration类的配置:

被依赖的类

测试类(需要被容器创建的类):

客户类(使用类)

运行结果:

四.Spring的优化

1.Spring注入propertis配置文件:

1.1无注解开发注入properties配置文件:

1.2有注解开发注入properties配置文件:

2.Spring注入第三方类

2.1无注解注入第三方类

2.2有注解注入第三方类

第一种方法:

第二种方法:

2.3在第三方类里面加入依赖类型

3.整合MyBatis:

3.1mybatis的复习

3.2整合操作分析:

3.3.Spring注解方式整合MyBatis具体操作

1.环境准备:

JDK:

Maven:

建立数据库表:

2.项目框架:

3.pom:

4.数据源的配置文件:MyBatis.properties:

5.pojo类:

6.Mapper类

7.实现接口:

8.实现类:

9.Jdbc配置类:

10.Mybatis配置类:

11.核心最重要:Spring配置类 !!!

12.测试类

13.测试结果:

4.AOP面向切面编程:

面向切面编程来源和概念:

项目框架:

pom.xml

实现的接口 和实现的类如下:

MyAdvice类的书写:

SpringBeanConfiguration的书写

客户类(使用类)

运行结果:

5.Spring整合SpringMVC

SpringConfig类:

SpringMVC类:

ServletContainerIniti类:

SpringMVCConfig类:


一.Spring的来源

其实spring的来源就是一个词语,完全解耦,为什么叫做完全解耦,还得从两个类的调用说起,接口1的实现类,我们叫做类1,接口2的实现类,我们叫做类2,现在我们有一个前提条件,就是,类2里面去new类1,且把类1的方法给到类2使用,我们现在形容类2和类1有依赖关系,也就是类2要依赖类1,那么如果出现一个境况也就是如果类1发生了改变,那么我们如何去使用类2,那我们在使用类2的时候就需要去改变类2里面的代码,一方面需要从新new一次类1,二方面需要把类2里面的方法对应新的类1的方法。此时这样的依赖之间的耦合性就会非常高。所以我们就有了一个策略,类2里面写new接口1,也就是在类二里面写一个set方法,这个方法的传参是一个实现类,方法的内容是把传入的实现类给到类2里面new的接口1,也就是说类2可以通过set的方法给类2里面new的接口1变成实现类1,这样就在我们每一次new 类2的时候,只需要new类2后,调用一次set方法就可以实现类2里面new类1,这样我们就实现了不用每次更改接口1的实现类的时候需要在类2里面修改代码了,我们就实现了一个解耦。

什么是耦合性:

类1实现接口1 类2实现接口2 而类2里面创建了类1,且把类1的方法调用在类2的方法中

1.耦合代码如下:

Interface1:

package com.dao;
​
public interface Interface1 {
    public void method1();
}
​


Class1:

package com.service;

import com.dao.Interface1;

public class Class1 implements Interface1 {
    @Override
    public void method1() {
        System.out.println("this is class1");
    }
}


Interface2:

package com.dao;

public interface Interface2 {
    public void method2();
}


Class2:

package com.service;
​
import com.dao.Interface1;
import com.dao.Interface2;
import org.eclipse.tags.shaded.org.apache.bcel.generic.NEW;
​
public class Class2 implements Interface2 {
    private Interface1 cl1 = new Class1();
    
    @Override
    public void method2() {
        cl1.method1();
    }
}
​

客户使用类:

package com.tang;
​
import com.service.Class2;
​
public class ClientUseClass {
    public static void main(String[] args){
        Class2 class1 = new Class2();
        class1.method2();
    }
}

如上明显是有耦合性的两个类,一旦类1的代码需要改变,类2也得需要重新new,且重新把类1的方法放入类2的方法,

这样耦合性太高代码的使用就会很麻烦,所以就出现了如下的解决方法:

2.解耦合代码如下:
Interface1:

package com.dao;
​
public interface Interface1 {
    public void method1();
}
​


Class1:

package com.service;
​
import com.dao.Interface1;
​
public class Class1 implements Interface1 {
    @Override
    public void method1() {
        System.out.println("this is class1");
    }
}
​

Interface2:

package com.dao;

public interface Interface2 {
    public void method2();
}


Class3

package com.service;

import com.dao.Interface1;
import com.dao.Interface2;

public class Class3 implements Interface2 {
    private Interface1 cl1;

    public void setClass (Interface1 m1){
        this.cl1 = m1;
    }

    @Override
    public void method2() {
        cl1.method1();
    }
}

客户使用类:

package com.tang;

import com.service.Class1;
import com.service.Class2;
import com.service.Class3;

public class ClientUseClass {
    public static void main(String[] args) {
        Class3 cl3 = new Class3();
        cl3.setClass(new Class1());
        cl3.method2();

    }
}

这样就发现我们的类3里面的类1的创建不是我们主动去改类3的代码,而是我们客户自己进行一个set,等于说,我们类的创建的方式不是我们手动创建了,而是我们去接受类,这样就从一个主观变成了被动,这样大大的减少了代码的耦合。

二.Spring的本质

本质其实就是完全解耦,用户通过容器来接受他们想要的类。就像我们把一些类放入到一个自动售卖机,我们

需要什么类就从里面拿,而不是自己去new。

基本概念:

这样我们类1的创建就有了这种方式创建,那么我们是不是也可以把类2的创建也可以这样创建呢,也是可以的,所以我们从上面来看,我们可以把类放在一个类似于set的这种结构和有客户new的结构里面,我们称这两种结构的总和叫做容器,也就是说我们可以通过容器来得到普通类,和有依赖关系的类,那么这些由容器创建的类叫做Bean,而这个解耦的技术叫做IOC,依赖反转技术,而用容器创建有依赖关系的类又叫做DI,也就是依赖注入,那么一下就出现了这几个名词,DI,IOC,bean,容器。

容器:创建类的一个封装的抽象概念。

bean:又容器创建的类的统称。

DI:由容器创建有依赖关系的类的技术,叫做依赖反转。

IOC:完全解耦,也就是包括有依赖关系的类的new和无依赖关系的new的统称的解耦的技术。

IOC技术是用容器放bean和DI。

而一个类可以依赖 简单数据类型 ,集合数据类型 , 引用数据类型 ,其实说白了都是类

三.Spring的使用

如何使用呢,刚才我们看到我们在使用多个类之间的关系的时候,我们在用Spring一共有几个必要的东西。

第一:得到无依赖的类。

接口1 类1 bean文件 bean的配置 获取类

第二:得到有依赖的类。

1.无Spring注解具体实现步骤:

1.1.大致步骤:
创建 接口1 类1 接口2 类2
写 bean文件
写bean的配置
获取类

1.2.有简单类型依赖和无依赖的类实现方式如下:

项目框架:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
​
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
​
  <groupId>com.tang</groupId>
  <artifactId>TestSpring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
​
  <name>TestSpring Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
​
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
​
  <dependencies>
​
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-servlet-api</artifactId>
      <version>10.0.4</version>
​
    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet.jsp</groupId>
      <artifactId>jakarta.servlet.jsp-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>jakarta.servlet.jsp.jstl</artifactId>
      <version>3.0.1</version>
    </dependency>
​
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
​
    <!--        Mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--        Mysql连接依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>
      
      
​
    <!--导入spring的context坐标,context依赖core、beans、expression-->
​
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.5.RELEASE</version>
      </dependency>
​
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
      </dependency>
​
​
​
  </dependencies>
​
  <build>
    <finalName>TestSpring</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean就是java对象 , 由Spring创建和管理-->
 <bean id="User" class="com.tang.pojo.TestUser">
     <property name="id" value="22"/>
     <property name="name" value="eddie"/>
     <property name="hobby" value="sports"/>
     <property name="age" value="22"/>
 </bean>
</beans>

测试类(需要被容器创建的类)

package com.tang.pojo;

public class TestUser {

    //封装数据 可以用alter + insert 的方式来放入
    private int id;
    private String name;
    private String hobby;
    private int age;

    //无参构造
    public TestUser(){
    }

    //有参构造
    public TestUser(int id, String name, String hobby, int age) {
        this.id = id;
        this.name = name;
        this.hobby = hobby;
        this.age = age;
    }

    //setter and getter
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    //toString的输出
    @Override
    public String toString() {
        return "TestUser{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", hobby='" + hobby + '\'' +
                ", age=" + age +
                '}';
    }

    public void printSometh(){
        System.out.println("this is from TestUserClass");
    }
}

客户类(使用者):

package com.tang.test;

import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUserClass {
    public static void main(String[] args) {
        //new ApplicationContext对象,记住要把ApplicationContent.xml要放入到文件里面
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
		//通过context.getBean来get类后我们去接收
        TestUser usr = (TestUser)context.getBean("User");
        usr.printSometh();


    }
}

运行结果:

1.3.有集合类型依赖的类实现方式如下:

项目框架:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
​
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
​
  <groupId>com.tang</groupId>
  <artifactId>TestSpring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
​
  <name>TestSpring Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
​
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
​
  <dependencies>
​
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-servlet-api</artifactId>
      <version>10.0.4</version>
​
    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet.jsp</groupId>
      <artifactId>jakarta.servlet.jsp-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>jakarta.servlet.jsp.jstl</artifactId>
      <version>3.0.1</version>
    </dependency>
​
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
​
    <!--        Mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--        Mysql连接依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>
      
     
    <!--导入spring的context坐标,context依赖core、beans、expression-->
​
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.5.RELEASE</version>
      </dependency>
​
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
      </dependency>
​
​
​
  </dependencies>
​
  <build>
    <finalName>TestSpring</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean就是java对象 , 由Spring创建和管理-->
     <bean id="User" class="com.tang.pojo.TestUser">
         <property name="id" value="22"/>
         <property name="name" value="eddie"/>
         <property name="hobby" value="sports"/>
         <property name="age" value="22"/>
     </bean>
    <bean id="ListUser" class="com.tang.pojo.TestListUser">
        <property name="strlist">
            <list>
                <value>yes</value>
                <value>no</value>
                <value>and</value>
            </list>
        </property>
    </bean>
</beans>

测试类(需要被容器创建的类)

package com.tang.pojo;
​
import java.util.List;
​
public class TestListUser {
    private List<String> strlist;
​
    public void setStrlist(List<String> strlist) {
        this.strlist = strlist;
    }
​
    @Override
    public String toString() {
        return "TestListUser{" +
                "strlist=" + strlist +
                '}';
    }
    public void printSomething(){
        System.out.println("this is testlistuser class");
    }
}
​
​

客户类(使用者):

package com.tang.test;
​
import com.tang.pojo.TestListUser;
import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class TestUserClass {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        TestListUser listUser = (TestListUser)context.getBean("ListUser");
        String s = listUser.toString();
        System.out.println(s);
        listUser.printSomething();
​
    }
}
​

运行结果:

1.4.有引用类型依赖的类实现方式如下:
项目框架:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
​
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
​
  <groupId>com.tang</groupId>
  <artifactId>TestSpring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
​
  <name>TestSpring Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
​
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
​
  <dependencies>
​
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-servlet-api</artifactId>
      <version>10.0.4</version>
​
    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet.jsp</groupId>
      <artifactId>jakarta.servlet.jsp-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>jakarta.servlet.jsp.jstl</artifactId>
      <version>3.0.1</version>
    </dependency>
​
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
​
    <!--        Mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--        Mysql连接依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>
​
    <!--导入spring的context坐标,context依赖core、beans、expression-->
​
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.5.RELEASE</version>
      </dependency>
​
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
      </dependency>
​
​
​
  </dependencies>
​
  <build>
    <finalName>TestSpring</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean就是java对象 , 由Spring创建和管理-->
     <bean id="User" class="com.tang.pojo.TestUser">
         <property name="id" value="22"/>
         <property name="name" value="eddie"/>
         <property name="hobby" value="sports"/>
         <property name="age" value="22"/>
     </bean>
​
    <bean id="ListUser" class="com.tang.pojo.TestListUser">
        <property name="strlist">
            <list>
                <value>yes</value>
                <value>no</value>
                <value>and</value>
            </list>
        </property>
    </bean>
​
    <bean id="DiUser" class="com.tang.pojo.TestDiUser">
        <property name="testUser" ref="User"/>
    </bean>
​
</beans>

测试类(需要被容器创建的类)
package com.tang.pojo;
​
public class TestDiUser {
​
    private TestUser testUser;
​
    public void setTestUser(TestUser testUser) {
        this.testUser = testUser;
    }
​
    public  void printsomething(){
        testUser.printSometh();
        System.out.println("this is a TestDiUser Class");
    }
}
​

客户类(使用者):

package com.tang.test;
​
import com.tang.pojo.TestDiUser;
import com.tang.pojo.TestListUser;
import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class TestUserClass {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        TestDiUser listUser = (TestDiUser) context.getBean("DiUser");
        listUser.printsomething();
​
​
    }
}
​

运行结果:

2.Spring注解具体实现步骤:

plus:Spring中的常用注解

@Component:使用在类上用于实例化Bean @Controller:使用在web层类上用于实例化Bean(作用于@Component一致) @Service:使用在service层类上用于实例化Bean(作用于@Component一致) @Repository:使用在dao层类上用于实例化Bean(作用于@Component一致) @Autowired:使用在字段上用于根据类型依赖注入 @Qualifier:结合@Autowired一起使用用于根据名称进行依赖注入 @Resource:相当于@Autowired+@Qualifier,按照名称进行注入 @Value:注入普通属性 @Scope:标注Bean的作用范围 @PostConstruct:使用在方法上标注该方法是Bean的初始化方法 @PreDestroy:使用在方法上标注该方法是Bean的销毁方法 以上的这些注解主要是替代 Bean 标签的配置。但是这些注解还不能全部替代xml配置文件,包括以下几个新注解:

@Configuration:用于指定当前类是一个Spring 配置类,当创建容器时会从该类上加载注解 @ComponentScan:用于指定Spring 在初始化容器时要扫描的包 @Bean:使用在方法上,标注将该方法的返回值存储到Spring 容器中 @PropertySource:用于加载.properties 文件中的配置 @Import:用于导入其他配置类

2.1.大致步骤:
创建 接口1 类1 接口2 类2
在需要new的类加上注解
写 bean文件
写bean的配置 : 扫描命令代码
获取类

2.2.1有简单类型依赖和无依赖的类实现方式如下:
项目框架:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
​
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
​
  <groupId>com.tang</groupId>
  <artifactId>TestSpring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
​
  <name>TestSpring Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
​
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
​
  <dependencies>
​
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-servlet-api</artifactId>
      <version>10.0.4</version>
​
    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet.jsp</groupId>
      <artifactId>jakarta.servlet.jsp-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>jakarta.servlet.jsp.jstl</artifactId>
      <version>3.0.1</version>
    </dependency>
​
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
​
    <!--        Mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--        Mysql连接依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>
​
    <!--导入spring的context坐标,context依赖core、beans、expression-->
​
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.5.RELEASE</version>
      </dependency>
​
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
      </dependency>
​
​
​
  </dependencies>
​
  <build>
    <finalName>TestSpring</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

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.tang.pojo"/>
</beans>

测试类(需要被容器创建的类)

package com.tang.pojo;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
@Component("testuser")
public class TestUser {
​
    @Value("eddie")
    private String id ;
​
    public void setId(String id) {
        this.id = id;
    }
​
​
    //无参构造
    public TestUser(){
    }
​
    public void printSometh(){
        System.out.println("this is from TestUserClass");
        System.out.println("this is the id : " + id);
    }
}
​

客户类(使用者)

package com.tang.test;
​
import com.tang.pojo.TestDiUser;
import com.tang.pojo.TestListUser;
import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class TestUserClass {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        TestUser testUser = (TestUser)context.getBean("testuser");
        testUser.printSometh();
    }
}
​

运行结果:

2.2.2有简单类型依赖和无依赖的类实现方式如下:优化版:

项目框架:

pom.xml

同上面没有优化的pom的配置一样

SpringBeanConfiguration类的配置:
package com.tang.config;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
​
@Configuration
@ComponentScan("com.tang.pojo")
public class SpringBeanConfiguration {
}
​

测试类(需要被容器创建的类)
package com.tang.pojo;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
@Component("testuser")
public class TestUser {
​
    @Value("eddie")
    private String id ;
​
    public void setId(String id) {
        this.id = id;
    }
​
​
    //无参构造
    public TestUser(){
    }
​
    public void printSometh(){
        System.out.println("this is from TestUserClass");
        System.out.println("this is the id : " + id);
    }
}

客户类(使用者)

package com.tang.test;
​
import com.tang.config.SpringBeanConfiguration;
import com.tang.pojo.TestDiUser;
import com.tang.pojo.TestListUser;
import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class TestUserClass {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringBeanConfiguration.class);
        TestUser testUser = (TestUser)context.getBean("testuser");
        testUser.printSometh();
    }
}
​

运行结果:

2.3.有集合类型依赖的类实现方式如下:
项目框架:

pom.xml

同上

SpringBeanConfiguration类的配置:
package com.tang.config;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
​
@Configuration
@ComponentScan("com.tang.pojo")
public class SpringBeanConfiguration {
}
​

测试类(需要被容器创建的类)
package com.tang.pojo;
​
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
​
import java.util.List;
​
@Component("testuser")
public class TestUser {
​
    @Value("eddie")
    private String id ;
​
    @Value("{hello,hello}")
    private List<String> list;
​
    public void setList(List<String> list) {
        this.list = list;
    }
​
    public void setId(String id) {
        this.id = id;
    }
​
​
    //无参构造
    public TestUser(){
    }
​
    public void printSometh(){
        System.out.println("this is from TestUserClass");
        System.out.println("this is the id : " + id);
        System.out.println("this is the list :" + list);
    }
}
​

客户类(使用者)
package com.tang.test;

import com.tang.config.SpringBeanConfiguration;
import com.tang.pojo.TestDiUser;
import com.tang.pojo.TestListUser;
import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUserClass {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringBeanConfiguration.class);
        TestUser testUser = (TestUser) context.getBean("testuser");
        testUser.printSometh();
    }
}

运行结果:

2.4.有引用类型依赖的类实现方式如下:

项目框架:

pom.xml

同上

SpringBeanConfiguration类的配置:
package com.tang.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.tang.pojo")
public class SpringBeanConfiguration {
}

被依赖的类

package com.tang.mapper;

import com.tang.pojo.User;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.List;

@Repository   //这里注意也需要加上注解加载到bean中 
public interface Mapper {


    List<User> getListUser();

    int insertUser(User user);



}

测试类(需要被容器创建的类):
   package com.tang.pojo;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;

    @Component("testdiuser")
    public class TestDiUser {

        @Autowired
        private TestUser testUser;

        public void setTestUser(TestUser testUser) {
            this.testUser = testUser;
        }

        public  void printsomething(){
            testUser.printSometh();
            System.out.println("this is a TestDiUser Class");
        }
    }

客户类(使用类)
package com.tang.test;
​
import com.tang.config.SpringBeanConfiguration;
import com.tang.pojo.TestDiUser;
import com.tang.pojo.TestListUser;
import com.tang.pojo.TestUser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class TestUserClass {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringBeanConfiguration.class);
        TestDiUser testdiuser = (TestDiUser) context.getBean("testdiuser");
        testdiuser.printsomething();
    }
}
​

运行结果:

四.Spring的优化

优化就是用spring这个ioc的思想和实现来new一下和整合一下我们经常用的东西。

比如我们用spring容器来整合mybatis,创建propertis类,整合springmvc。

1.Spring注入propertis配置文件:

如何用注解开发或者说用spring注入开发的方式来做到注解开发呢?

1.1无注解开发注入properties配置文件:

在bean文件中加入:

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

    <context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties,classpath:filePath.properties"/>


<context:property-placeholder 
	location="属性文件,多个之间逗号分隔"  
    file-encoding="文件编码"  
	ignore-resource-not-found="是否忽略找不到的属性文件"  
	ignore-unresolvable="是否忽略解析不到的属性,如果不忽略,找不到将抛出异常"  
	properties-ref="本地Properties配置"  
	local-override="是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性,否则相反"  
	system-properties-mode="系统属性模式,默认ENVIRONMENT(表示先找ENVIRONMENT,再找properties-ref/location的),NEVER:表示永远不用ENVIRONMENT的,OVERRIDE类似于ENVIRONMENT"  
	order="顺序"  
        />

1.2有注解开发注入properties配置文件:
@PropertySource("classpath:data.properties")
2.Spring注入第三方类

注入第三方类的意思是,我们需要注入到容器里面的类不是在我们new的实现类和实现接口里面,而是我们

自己需要从外部加载进来的类。

我们这里如下的举例就用我们在整合Mybatis时需要把datasource数据源放入到容器中

2.1无注解注入第三方类

<?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">
<!--管理DruidDataSource对象-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql:///library?useSSL=false"/>
    <property name="username" value="root"/>
    <property name="password" value="1234"/>
</bean>
</beans>
2.2有注解注入第三方类

第一种方法:

把第三方类写一个类出来如下:

这里的重点的是 不是说bean这个类就不像之前不是第三方类那样是直接在类上面表controller,service,component,reposity这样,而是在一个可以返回类的方法上去做这个操作。

package com.tang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.tang.dao.testaops;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;



public class JdbcConfig {

    @Value("${jdbc.driver}")
    public String driver;

    @Value("${jdbc.url}")
    public String url;

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

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

    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

在bean类里面需要写如下import的配置:

package com.tang.config;

import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("com.tang")
@EnableAspectJAutoProxy
@PropertySource("classpath:mybatisconf.properties")
//如下必须配置一个import 
@Import(JdbcConfig.class)
public class springbeanconfig {
}

第二种方法:

把第三方类写一个类出来如下:

注意这里是加了configuration

@configuration
package com.tang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.tang.dao.testaops;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;



public class JdbcConfig {@Value("${jdbc.driver}")
public String driver;

@Value("${jdbc.url}")
public String url;

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

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

@Bean
public DataSource dataSource(){
    DruidDataSource ds = new DruidDataSource();
    ds.setDriverClassName(driver);
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    return ds;
}
                         }

}

在bean的配置里面一定要配上扫描

@ComponentScan({"com.tang.config","com.tang.pojo","com.tang.dao"})





package com.tang.config;

import org.springframework.context.annotation.*;

@Configuration
@ComponentScan({"com.tang.config","com.tang.pojo","com.tang.dao"})
@EnableAspectJAutoProxy
@PropertySource("classpath:mybatisconf.properties")
//如下必须配置一个import
@Import(JdbcConfig.class)
public class springbeanconfig {
}

总结就是要么就是在第三方类配置上configuration,然后bean类配上扫描,要么第三方类不配置,就在bean类里面import即可

2.3在第三方类里面加入依赖类型

通过传参的方式放入第三方bean类如下:

 @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){ //这里就是传入的依赖的类
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

3.整合MyBatis:

3.1mybatis的复习

jdbc就5步:

获取mysql驱动

得到connection对象

得到statement执行语句对象

得到结果集对象resultset

得到结果

从而衍生到mybatis的四步

前提条件是写好配置文件和一个mapper也就是sql语句的文件:

sqlsessionfactory.builder()里面加入配置文件得到sqlsessionfactory

调用opensession的方法后得到sqlsession 也就是是类似于得到一个preparestatement类

用sqlsession对象去调用delete update select 方法,而如果是查询和更新的话 直接把放入数据库的类和

需要查询依据的数据字段和需要放入的内容放入这些方法中,被sqlsesion调用后,会操作进入数据库从而直接得到结果

如上是其中一种方法,还有一种方法是:

sqlsessionfactory.builder()里面加入配置文件得到sqlsessionfactory

调用opensession的方法后得到sqlsession 也就类似于得到一个preparestatement类

sqlsession调用getmapper后得到dao对象

对象执行对应的语句得到结果或者把数据传入数据库中

这两种方法的对比其实就是一个是把操作类集成了一个具体的类 这个具体的类里面的方法

的名字也就是配置文件对应的sql语句的id,而方法的传参就是语句执行传入数据库的值或者是

查询的依据对象,而方法返回的值是语句执行的结果。

具体实现方法可以参考下面老师写的博客:

Mybatis实现增删改查mybatis增删改查code袁的博客-CSDN博客

而这其中mybatis的得到dao对象其实就是

mybatis里面的mapper.xml的namespace 对应 dao的类名 , mapper.xml里面的 id 对应dao的方法名

把一个dao类里面的多个方法对应 增删改查的方法mapper.xml里面的sql语句:

方法的传参就是放到数据库里面的东西,方法的返回值就是从数据库里面拿出来的东西

而方法名和mapper.xml里面的id名对应即可

3.2整合操作分析:

所以在整合mybatis的时候要主要是去整合如下代码:


inputstream in = Resource.getResourceAsStream("mybatisConfi.xml");

SqlsessionFactroy sqlsessionfactory = new SqlSessionFactoryBuilder().build("in");



SqlSession sqlsession = sqlsessionfactory.opensession();

Mapper mapper = sqlsession.getMapper("mapper.xml");

List<User> list = mapper.getListUser();

把所有的步骤分为了两大块,第一块就是上面两行代码,第二块就是下面的两行代码:

那么先从第一块代码开始:

首先是数据源,也就是放入build的配置文件,配置文件里面有jdbc需要的配置和

1) 声明数据源DataSource,使用阿里的Druid连接池 2) 声明SqlSessionFactoryBean类,在这个类的内部创建SqlSessionFactory对象

3) 声明MapperScannerConfigurer类,在这个类的内部创建dao代理对象,创建的对象放在spring容器中 4) 声明service对象,把3)中的dao赋值给service对象属性

这里注意个细节,在原生mybatis开发中,创建sqlSessionFactory对象是需要mybatis-config.xml的,我们回顾,该配置文件中主要书写了三部分信息:

mybatis-config.xml 1.dataSource 记载数据库的连接信息 2.typeAliases 配置实体别名 3.mapper映射文件的注册

同理,使用SqlSessionFactoryBean来创建sqlSessionFactory对象,也需要这部分信息,需要这些,即依赖这些,就可以通过注入属性的方式得到这些信息。我们采用set注入的方式。

上面的三部分信息对应着SqlSessionFactoryBean的三个属性 1.dataSource–》指向数据库连接的配置 2.typeAliasesPackage–》指向实体类的包,可为该包下的所有类创建类名首字母小写的别名 3.mapperLocations–》值为通配符表达式,对所有匹配上的Mapper文件进行注册

此时mybatis-config.xml中的所有信息都通过注入的方式写到spring的配置文件中去了,所以mybatis-config.xml就可以不用了。

MapperScannerConfigurer spring提供MapperScannerConfigurer类来封装第二部分代码,用于生成userDao对象。 在原生开发步骤中,我们需要是用sqlSessionFactory对象来获得sqlSession对象,再指定XXXDao的class,进而获得对应的dao对象。 在spring的封装下,我们只需要在配置文件中对MapperScannerConfigurer进行配置,

sqlSessionFactoryBeanName-》sqlSessionFactory对象需要被注入 basePackage-》指定DAO接口所在的包

<?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.tjise.bean"/>-->
    <!-- 加载数据库连接信息的属性文件 -->
    <context:property-placeholder location="classpath:jdbc-config.properties"/>
        <!-- 配置Druid数据源的Bean -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

    </bean>


    <!-- 配置SessionFactory的Bean -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>

        <!-- 指定MyBatis配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis.xml"/>

        <!-- 给实体类起别名 -->
        <property name="typeAliasesPackage" value="com.tjise.entity"/>

    </bean>

    <!-- 配置mapper接口的扫描器,将Mapper接口的实现类自动注入到IoC容器中
     实现类Bean的名称默认为接口类名的首字母小写 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <!-- basePackage属性指定自动扫描mapper接口所在的包 -->
        <property name="basePackage" value="com.tjise.mapper"/>

    </bean>
</beans>




从上面的mybatis复习和用无注解spring整合mybatis可以看出,其实就是用容器的方式,

把sqlsessionfactoryBuilder(mybatisconfig.xml) 和 sqlsessionfactory.opensession() 用 sqlsessionfactorybean来代替

而 sqlsession.getmapper 的操作 用mapperscannerconfigurer 类来代替

这两个类里面又分别由datasource 和 mapper需要创建,所以 最后就整合成了 创建这两个类,在用spring创建这两个

类的过程中就是其实就做了这些操作。所以推断的意思是在bean中依赖注入这些类的时候就是在做如上几步操作。

总结一下:

1.

bean注入sqlsessionfactorybean和mapperscannerconfigurer => 也就是在new前面两个类的过程中有操作如下步骤sqlsessionfactoryBuilder(mybatisconfig.xml) 和 sqlsessionfactory.opensession() sqlsession.getmapper =>

所以最后mapper也就是实现的mapper接口,可以通过spring获取,如果需要获取实现类,就在依赖注入一次实现类即可。

往下推

2.

就是在依赖注入这如上两个类的过程中,有一些依赖也需要写到bean中,如注入 sqlsessionfactorybean时就有

dataSource类,configLocation变量,和 typeAliasesPackage。所以需要注入一次datasource,又因为datasoure的value依赖于一个properties文件所以要配置 <context:property-placeholder location="classpath:jdbc-config.properties"/>。

而在注入mapperscannerconfigurer时候又需要一个 dao,所以也要写到bean里面去。

那么汇总就需要在bean中写

  1. <context:property-placeholder location="classpath:jdbc-config.properties"/>

  2. datasource 包括 datasoure的value

  3. sqlsessionfactorybean 包括 datasource typeAliasesPackage configLocation

  4. mapperscannerconfigurer dao

3.

最后再就是走到了更简单的spring注入整合mybatis,也就是用第三方类和配置类来代替bean配置。

那么datasource需要一个类, sqlsessionfactorybean需要一个类,mapperscannerconfigurer需要一个类。

所以最后我的案例就是最简单的spring注入整合mybatis如下:

3.3.Spring注解方式整合MyBatis具体操作
1.环境准备:

JDK:

Maven:

建立数据库表:

2.项目框架:

3.pom:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.tang</groupId>
  <artifactId>Test</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Test Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-servlet-api</artifactId>
      <version>10.0.4</version>



    </dependency>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>jakarta.servlet.jsp</groupId>
      <artifactId>jakarta.servlet.jsp-api</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>jakarta.servlet.jsp.jstl</artifactId>
      <version>3.0.1</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!--        Mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--        Mysql连接依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.23</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.7</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
    <!-- spring aop支持 -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.3.23</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>6.0.11</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.16</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>TestReview</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

4.数据源的配置文件:MyBatis.properties:

这里注意连接词是&,还有时区是serverTimeZone=UTC

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/***?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC

//上面*** 是你对应的表的名称

jdbc.username=root
jdbc.password=****** 

//这里填自己的密码

5.pojo类:

package com.tang.pojo;

public class User {
    private int id;
    private int age;
    private String name;


    public User(){

    }

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

6.Mapper类

package com.tang.mapper;

import com.tang.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
import java.util.List;

public interface Mapper {

    @Select("select * from test_table")
    List<User> getListUser();

    @Insert("insert into test_table(id,age,name) values(#{id},#{age},#{name})")
    int addUser(User user);
}

7.实现接口:

package com.tang.mapper;

import com.tang.pojo.User;

import java.util.List;

public interface TestMapper {

    List<User> getUsers();

    int addUsers(User u);

}

8.实现类:

package com.tang.service;

import com.tang.mapper.Mapper;
import com.tang.mapper.TestMapper;
import com.tang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestMapperImple implements TestMapper {

    @Autowired
    private Mapper mapper;

    public void setMapper(Mapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public List<User> getUsers() {
        return mapper.getListUser();
    }

    @Override
    public int addUsers(User u) {
        return mapper.addUser(u);
    }
}

9.Jdbc配置类:
package com.tang.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.sql.Driver;

public class JdbcConfig {

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

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

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

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

    @Bean
    public DataSource dataSource (){
        DruidDataSource  ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return  ds;

    }

}

10.Mybatis配置类:
package com.tang.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.tang.mapper");
        return msc;
    }
}

11.核心最重要:Spring配置类 !!!

package com.tang.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:MyBatisConfig.properties")
@ComponentScan("com.tang")
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {
}

12.测试类

package com.tang.test;

import com.tang.config.SpringConfig;
//import com.tang.service.MapperImple;
import com.tang.pojo.User;
import com.tang.service.TestMapperImple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new  AnnotationConfigApplicationContext(SpringConfig.class);
        TestMapperImple mp = (TestMapperImple) context.getBean(TestMapperImple.class);
         List<User> list = mp.getUsers();
         for(User u : list){
             System.out.println(u);
         }
    }
}

13.测试结果:

4.AOP面向切面编程:

面向切面编程来源和概念:

首先还是来源是哪里,首先,在我们编写mybatis的时候,我们有一个mapper的类,而这个类最后是sqlsession返回的一个类,这个类的方法名对应着增删改查的操作步骤,可以总结为,mapper.xml文件对应了方法名,而这个mapper类执行对应的方法就是执行对应的sql语言,而sql语言也同样和方法一样,有一个输入和输出,输入就是模糊查询需要的字段,或者需要加入数据库的数据,而输出比如说是查询的结果。

总之:就是mapper.xml里面的 namespce = mapper.class

id = mapper.class里面对应的方法

就这样形成了一个对应,我们在通过sqlsession得到这个mapper的类的时候,我们操作这个类的方法其实就是操作

数据库的sql语句。

那么这个类这么重要,这个类对应了许多方法,那如果每个方法都有同样的代码,那我们就把他抽离出来,而

把这相同的代码叫做advice , 所有的方法叫做 joinpoint,而需要用同一advice的方法就叫做pointcut,

最后advice + pointcut 就叫做 Aspect

Advice 的类型

before advice, 在 join point 前被执行的 advice. 虽然 before advice 是在 join point 前被执行, 但是它并不能够阻止 join point 的执行, 除非发生了异常(即我们在 before advice 代码中, 不能人为地决定是否继续执行 join point 中的代码)

after return advice, 在一个 join point 正常返回后执行的 advice

after throwing advice, 当一个 join point 抛出异常后执行的 advice after(final) advice, 无论一个 join point 是正常退出还是发生了异常, 都会被执行的 advice. around advice, 在 join point 前和 joint point 退出后都执行的 advice. 这个是最常用的 advice. introduction,introduction可以为原有的对象增加新的属性和方法。

所以每一次我们编写有很多jointpoint的方法的类的时候,我们需要把切面单独拿出来,这样

我们写代码就不会那么的浪费资源,同一advice可以有不用的pointcut使用。

而使用方法就是把pointcut和advice 写在一个切面类中,把这个类标注切面和bean最后被spring容器扫描从而

注入到容器里面即可。其他的实现类的步骤就按正常的从spring得到类的操作正常进行即可。

项目框架:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
​
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
​
    <groupId>com.tang</groupId>
    <artifactId>TestMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
​
    <name>TestMybatis Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
​
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
​
    <dependencies>
​
        <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>10.0.4</version>
​
        </dependency>
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>jakarta.servlet.jsp</groupId>
            <artifactId>jakarta.servlet.jsp-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
            <version>3.0.1</version>
        </dependency>
​
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
​
        <!--        Mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!--        Mysql连接依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
​
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.23</version>
        </dependency>
​
​
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
        <!-- spring aop支持 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.23</version>
        </dependency>
​
​
    </dependencies>
​
    <build>
        <finalName>TestReview</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

实现的接口 和实现的类如下:

接口:

package com.tang.dao;

public interface testaops {
    public void printyes();

    public void printno();


}

实现类:

package com.tang.service;


import com.tang.dao.testaops;
import com.tang.test.TestAop;
import org.springframework.stereotype.Service;

@Service
public class testaopsimpl implements testaops {
    @Override
    public void printyes() {
        System.out.println("yes");
    }

    @Override
    public void printno() {
        System.out.println("no");
    }
}

MyAdvice类的书写:

其实就是在aop的注解编程里面,其实可以把aop的切面当成一个类也是要放到bean容器里面

只是最后得到实现类的时候,调用实现类里面的方法时候会使用这个类的通知一并被调用。

但是值得注意的是这里的切点的标注是实现类的方法。

package com.tang.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class MyAdvice {

    @Pointcut("execution(void com.tang.service.testaopimple.getAge())")
    private void pt(){}

    @Before("pt()")
    public void before(){
        System.out.println("============");
    }
}

SpringBeanConfiguration的书写

这里注意这里的componentscan一定要把切面所在的类扫到。


package com.tang.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.tang")
@EnableAspectJAutoProxy
public class springbeanconfig {
}


客户类(使用类)

这里需要注意在getbean时候,这里放入的类不是实现类,而是接口类。这个地方和在切面类的切点的标注那里,都有点疑问,在后续学源码的时候再看看是什么原因。

package com.tang.test;
​
import com.tang.config.springbeanconfig;
import com.tang.dao.testaop;
import com.tang.dao.testaops;
import com.tang.service.testaopsimpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class testAops {
    public static void main(String[] args) {
       ApplicationContext context = new  AnnotationConfigApplicationContext(springbeanconfig.class);
       testaops test  = (testaops)context.getBean(testaops.class);
       test.printno();
       test.printyes();
    }
}

运行结果:

5.Spring整合SpringMVC

很简单:四个大类:

SpringConfig类:

package com.tang.config;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
​
@Configuration
@ComponentScan({"com.tang.service"})
@PropertySource("classpath:jdbc.properties")
@Import({DataSource.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
​

SpringMVC类:

package com.tang.config;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
​
@Configuration
//@ComponentScan({"com.tang.service","com.tang.controller"})
@ComponentScan({"com.tang.controller"})
@EnableWebMvc
​
public class SpringMVC {
}

ServletContainerIniti类:

package com.tang.controller;
​
import com.tang.config.SpringConfig;
import com.tang.config.SpringMVC;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
​
​
public class ServletContainerIniti extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
​
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMVC.class};
    }
​
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

SpringMVCConfig类:

package com.tang.controller;
​
import com.tang.pojo.Book;
import com.tang.pojo.User;
import com.tang.service.MapperService;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
​
import java.util.ArrayList;
import java.util.List;
​
@RestController
@RequestMapping("/users")
public class SpringMVCConfig {
    @Autowired
    private MapperService mapperService;
​
    @PostMapping
    public Result save(User user){
        boolean flag = mapperService.save(user);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
​
​
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = mapperService.delete(id);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
​
    @PutMapping
    public Result update(User user){
        boolean flag = mapperService.update(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR , flag);
    }
​
    @GetMapping("/{id}")
    public Result getUser(@PathVariable Integer id){
        User user =  mapperService.getById(id);
        if(user == null){
            return new Result(Code.GET_ERR,null);
        }
        return new Result(Code.GET_OK,user);
    }
​
    @GetMapping
    public Result getAll(){
        List<User>  users =  mapperService.getAll();
        if(users == null){
            return new Result(Code.GET_ERR,null);
        }
        return new Result(Code.GET_OK,users);
    }
}
​

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于全网详细的VSCode教程,以下是一个简短的描述: 全网详细的VSCode教程应该包含以下内容:基本介绍、安装和设置、编辑器布局、常用快捷键、实用插件和扩展、调试功能、版本控制、代码片段等。 在基本介绍部分,应该详细介绍VSCode是什么,它的优点和特点,如何下载和安装等。 安装和设置部分应该涵盖不同操作系统上的安装步骤和注意事项。同时,还应该介绍不同配置选项,如主题、字体、缩进设置等。 编辑器布局部分应该解释各个面板和视图的作用,如侧边栏、编辑窗口、终端等。详细说明如何调整布局以优化工作流程。 常用快捷键部分应该列举常用的快捷键和相关操作,如快速打开文件、搜索、查看定义等。应该对不同功能区分操作系统进行说明。 实用插件和扩展部分应该介绍一些常见和有用的插件,如代码片段、代码格式化、调试器等。应该详细解释如何安装和使用这些插件。 调试功能部分应该详细介绍如何配置和使用调试器,包括设置断点、查看变量的值等。 版本控制部分应该介绍如何使用内置的版本控制工具,如Git,如何提交、推送和拉取代码等。 最后,代码片段部分应该教授如何创建和使用代码片段,以提高编码效率。 以上仅是对全网详细的VSCode教程的一些简要描述。当然,真正最详细教程可能比这个更加全面和详细,具体内容可能还包括更多高级功能和技巧。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值