SpringBoot框架学习-基础篇

SpringBoot框架基础

一、概念

1.为什么要使用SpringBoot?
因为Spring、SpringMVC需要使用大量的配置文件,配置各种对象,再把对象放入Spring的容器中才能使用,并且需要了解其他框架配置的规则。SpringBoot则已经配置好了,省去了繁琐的配置文件,可以直接使用(相当于不需要配置文件的Spring+SpringMVC)。

1.1 特点
  • 1.Springboot:创建Spring应用,也是一个容器。
  • 2.内嵌了Tomcat、Jetty、Undertow服务器。
  • 3.提供了starter起步(默认)依赖,简化应用的配置(比如使用Mybatis框架,需要在Spring中配置Mybatis的SQLSessionFactory对象、Dao的代理对象。在Springboot中只需要添加mybatis-spring-boot-starter依赖包,默认都配置完成)。
  • 4.自动配置,尽可能的配置Spring和第三方库(在spring中将对象都创建好,并放入Spring容器中,可以直接使用)。
  • 5.提供了健康检查(提供一些模块对于程序的运行状态进行检查)、统计、外部化配置(比如config.properties)。
  • 6.不用生成代码,不用使用xml做配置。
1.2 启动
  • pom配置
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.2</version>
    <relativePath/>
  </parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  • controller类
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @RequestMapping("hello")
    @ResponseBody
    public String hello(){
        return "Springboot第一步开始";
    }
}
  • 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
  • 访问地址
http://localhost:8080/hello

二、注解

2.1 @SpringBootApplication

复合注解,由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解组成。

  • @SpringBootConfiguration:
    复合注解,包含@Configuration注解。被注解的类可以作为配置文件使用。可以通过@Bean申明对象,注入到容器。
  • @EnableAutoConfiguration:
    启用自动配置,把JAVA对象配置好,注入到Spring容器中。例如,把mybatis对象创建好放入容器中。
  • @ComponentScan:
    扫描器(扫描指定包下的注解),根据注解的功能创建对象,给属性赋值等。默认扫描@ComponentScan所在类所在的包及其子包。
2.2 @Value
  • 作用:读取配置文件的值,给属性赋值。
  • 用法:Value(“${key}”),key来自application配置文件。

完整用例

  • 配置文件
server:
  port: 8082
  servlet:
    context-path: /myDev
#自定义属性
school:
  name: 第一中学
  • conroller类
@Controller
public class MyController {
	//school.name配置文件的key;null读取不到key时赋值null。
    @Value("${school.name:#{null}}")
    private String name;

    @RequestMapping("hello")
    @ResponseBody
    public String hello(){
        return "@Value读取配置文件"+name;
    }
2.3 @ConfigurationProperties
  • 作用:将整个文件映射成一个对象,用于自定义配置项比较多的情况。
  • 实例:
//实体类,用于映射配合信息(prefix对应配置文件内映射对象的首标识)
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
	//属性名与配置文件映射的属性名一致
    private String name;
    private int age;
    private String sex;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}
  • 配置文件
student:
  name: 张三
  age: 24
  sex: 男
  • controller控制器
@Controller
public class MyController {
	//从容器中获取对象,并赋值
    @Resource
    private Student student;

    @RequestMapping("student")
    @ResponseBody
    public String student(){
        return "配置文件转换成对象=="+student;
    }
}

三、配置文件

3.1 配合文件类型

.yml:k: value
.properties:k=value

3.2 使用
3.2.1 主配置文件
  • application.properties
#设置访问端口
server.port=8081
#设置上下文访问路径
server.servlet.context-path=/myBoot

访问路径由”http://localhost:8080/hello“更改为http://localhost:8081/myBoot/hello

  • application.yml
server:
  port: 8082
  servlet:
    context-path: testBoot

访问路径由”http://localhost:8080/hello“更改为http://localhost:8082/testBoot/hello

3.2.2 多环境配置

springboot学之前要学spring吗_配置文件

  • application.yml
//根据需求选择不同配置文件
spring:
  profiles:
    active: dev

四、基础应用

4.1 jsp(不提倡使用,使用spring的模块化)

完整样例

  • controller类
@Controller
public class JSPController {
	//两个方法作用相同(name在视图中引用,返回的index视图名称)
    @RequestMapping("/myJsp")
    public String requestJSP(Model model){
        model.addAttribute("name","王伟");
        //视图的逻辑名称
        return "index";
    }

    @RequestMapping("/myJsp2")
    public String doJSP(HttpServletRequest request){
        request.setAttribute("name","王伟");
        return "index";
    }
}
  • pom.xml文件
//添加以下依赖
<!--  处理JSP的依赖 ( <dependencies>标签) -->
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

<!-- 指定JSP的存放目录(固定写法)(<build>标签)  -->
    <resources>
      <resource>
        <!-- 原本存放JSP的目录  -->
        <directory>src/main/webapp</directory>
        <!-- 编译后存放的目录  -->
        <targetPath>META-INF/resources</targetPath>
        <!-- 编译指定目录下的文件  -->
        <includes>
          <include>**/*.*</include>
        </includes>
      </resource>
    </resources>
  • 视图(index.jsp)
<body>
    <div>
        <h1>springboot-jsp:${name}</h1>
    </div>
</body>
4.2 SpringApplication
  • 作用:SpringApplication.run():返回的是Spring容器。
  • 应用:
public static void main(String[] args) {
 		//返回spring容器(ConfigurableApplicationContext的父接口ApplicationContext)
       ConfigurableApplicationContext  ctx= SpringApplication.run(Application.class,args);
       ctx.getBean("");
 }
4.3 CommandLineRunner接口、ApplicationRunner接口
  • CommandLineRunner接口和ApplicationRunner接口:执行时间是在容器创建后自动执行run方法。可以完成自定义的在容器创建好的一些操作。通过run方法执行。ApplicationRunner接口的run方法参数是ApplicationArguments,CommandLineRunner接口中run方法的参数是String数组。
4.4 拦截器
  • 拦截器是SpringMVC中一种对象,能拦截对controller的请求。SpringMVC框架中有系统的拦截器,还可以自定义拦截器,实现对请求预先处理。
  • 使用:实现接口HandlerInterceptor。
4.5 Servlet
  • 1.自定义Servlet类
  • 2.注册Servlet
  • 3.WebApplicationConfig配置类
4.6 过滤器Filter
  • 过滤器Filter:Filter是Servlet规范中的过滤器,可以处理请求,对请求的参数、属性进行调整。通常在过滤器中处理字符集。
  • 实现步骤:
    1)创建Filter对象
    2)注册Filter
    3)创建controller
4.7 字符集过滤器
  • CharacterEncodingFilter:解决post请求中乱码的问题。SpringMVC框架中是在web.xml注册过滤器,配置他的属性。
  • 步骤
    1)配置字符集过滤器
    2)在application.properties文件中修改server.servlet.encoding.enabled=false,作用是关闭Springboot框架的默认配置,使用自定义过滤器CharacterEncodingFilter。
  • 通过配置文件application设置编码方式
# true:使用框架设置好的配置
server.servlet.encoding.enabled=true
#设置编码
server.servlet.encoding.charset=utf-8
#设置请求和返回的编码设置为charset属性的值(也可以单独设置请求或返回的编码)
server.servlet.encoding.force=true

五、ORM操作数据库

5.1 Springboot + Mybatis

在Springboot框架中集成Mybatis,通过Mybatis框架操作数据库数据。

  • 使用步骤:
    1)Mybatis起步依赖:完成Mybatis对象的自动配置,并将对象放入容器中
    2)pom.xml指定把src/main/java目录中的xml文件包含到classpath中
    3)创建实体类(映射数据库表)
    4)创建dao接口,并创建操作数据库的接口方法
    5)创建dao文件对应Mapper文件(.xml),编写接口方法对应功能的SQL
    6)创建service层对象,调用对应的dao层方法,去调用数据库数据
    7)创建controller层,去处理前端的请求,并调用service层方法,处理后做出请求响应

完整实例

  • pom.xml配置文件(添加依赖、插件等配置)
<!-- 父依赖  -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.10.RELEASE</version>
        <relativePath/>
    </parent>
<!-- JDK版本设置 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
<!-- web项目的初始依赖 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!-- springboot的测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!-- mybatis的初始依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
<!-- postgresql数据库依赖 -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.22</version>
        </dependency>
    </dependencies>
    <build>
<!--  加载指定目录下的文件  -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
<!--  springboot打包插件   -->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • 数据库中表对应实体类
public class Student {
    private int id;
    private String name;
    private int age;
    private String email;

    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}
  • dao接口
import com.xqj.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface StudentDao {
    Student selectStudent(@Param("id") Integer id);
}
  • 到接口对应的Mapper文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xqj.dao.StudentDao">
    <!--namespace根据自己需要创建的的mapper的路径和名称填写-->
    <select id="selectStudent" resultType="com.xqj.pojo.Student">
        select id,name,age,email from student where id=#{id}
    </select>
</mapper>
  • Service层接口与实现
public interface StudentSrtvice {
    Student findStudent(Integer id);
}

//接口实现类
@Service
public class StudentServiceImpl implements StudentSrtvice {
    @Resource
    private StudentDao studentDao;
    @Override
    public Student findStudent(Integer id) {
        Student student = studentDao.selectStudent(id);
        return student;
    }
}
  • controller控制层
@Controller
public class StudentController {
    @Resource
    private StudentSrtvice studentSrtvice;
	
    @RequestMapping("/student/select")
    @ResponseBody
    public Student getStudent(Integer id){
        Student student = studentSrtvice.findStudent(id);
        return student;
    }
}
  • 主配置文件
#服务信息
server.port=8080
server.servlet.context-path=/myBoot
#数据库连接信息
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/****
spring.datasource.username=****
spring.datasource.password=****

//访问地址
http://localhost:8080/myBoot/student/select?id=1

5.2 @Mapper和@MapperScan
5.2.1 @Mapper
  • @Mapper:将类通过注解成代理对象注入容器。一次只能注解一个对象,在注解的类的上方使用。
5.2.2 @MapperScan
  • @MapperScan:可以一次性注解一个或多个包下的对象。在容器初始化的类的上方使用。找到dao接口和Mapper文件。
  • 使用:@MapperScan(basePackages=“”)或@MapperScan(basePackages={“”,“”})
5.2.3 dao接口与Mapper文件的分开管理
  • 作用:将Mapper的.xml文件放在resources目录下任意自定义包中。通过配置文件进行绑定。
  • 使用:在application配置文件中设置属性mybatis.mapper-location=classpath:resources下自定义目录/*.xml
  • 步骤:
    1)在resources目录下创建子目录,用于存放.xml文件
    2)把mapper文件放在创建的子目录中
    3)在application主配置文件中指定文件的目录
    4)在pom.xml文件中吧resources目录中的文件编译到目标目录中。
<resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
    </resources>