Springboot学习笔记(一)

前言

最近我们学校进行了实训,学习了springboot,在此之前我自学过一段时间,所以这一次在实训的过程中尝试结合实训老师教的和自己所学的来写一篇学习笔记。

1.Springboot介绍

Spring Boot是一个便捷搭建基于spring工程的脚手架;作用是帮助开发人员快速搭建大型的spring 项目。简化工程的配置和依赖管理;开发人员把时间都集中在业务开发上。

并且我们可以从Springboot简介中看到下面一段话:Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront
confifiguration of Spring. Spring Boot takes an opinionated view of building production-ready applications.

这段话翻译过来的意思是:Spring Boot的设计目的是让您尽可能快地启动和运行,而无需预先配置Spring。Spring Boot以一种固定的方式来构建可用于生产级别的应用程序。

我们一般把Spring Boot称为搭建程序的脚手架或者说是便捷搭建基于Spring的工程脚手架。其最主要作用就是帮助开发人员快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让开发人员关注业务而非配置。

2.Springboot的特点

1.为基于Spring的开发提供更快的入门体验
2.开箱即用,没有代码生成,也无需XML配置。同时也可以修改默认值来满足特定的需求。
3.提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。
4.Spring Boot并不是不对Spring功能上的增强,而是提供了一种快速使用Spring的方式。

3.为什么要学习Spring Boot

java一直被人诟病的一点就是臃肿、麻烦。当我们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,究其原因注意是两点:
1. 复杂的配置
项目各种配置其实是开发时的损耗, 因为在思考 Spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。

2.混乱的依赖管理
项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库
的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程
序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

而Spring Boot让这一切成为过去!Spring Boot 简化了基于Spring的应用开发,只需要“run”就能创建一个独立的、生产级别的Spring应用。
Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认设置,存放默认配置的包就是启动器
starter),这样我们就可以简单的开始。多数Spring Boot应用只需要很少的Spring配置。

我们可以使用Spring Boot创建java应用,并使用java –jar 启动它,就能得到一个生产级别的web工程。

4.Springboot入门案例

项目结构

4.1 创建Springboot项目

idea->file->new->project 选中 Srping Initializr,然后一直下一步就可以了

默认生成的Spring Boot项目;

  • java文件夹

  • resources文件夹中目录结构

    • static:保存所有的静态资源,例如: js,css ,images;

    • templates:保存所有的模板页面(Spring Boot默认jar包使用嵌入式的Tomcat,默认不支持JSP页面),可以使用模板引擎(freemarker、thymeleaf);

    • application.properties:Spring Boot应用的配置文件,可以修改一些默认设置;

4.2创建依赖

SpringBoot提供了许多“启动器”,启动器在类路径中添加依赖的jar包。

spring-boot-starter-parent是一个特别的启动器,里面已经对各种常用依赖的版本进行了管理,我们的项目需要以这个项目为父工程,这样我们就不用操心依赖的版本问题了。

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/>
    </parent>

    <groupId>com.xxx</groupId>
    <artifactId>springboot01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot01</name>
    <description>Demo project for Spring Boot</description>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!-- 启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency> 
        
         <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

        <!-- 增加web依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

由于添加web依赖后(spring-boot-starter-web),会发现tomcat、springboot、springmvc等依赖已经加进来了。所以Springboot项目不需要再像ssm一样需要额外的tomcat了。

4.3创建代码:

创建启动类Springboot01Application

在com/xxx包中创建启动类,这个类要和controller同级

springboot启动原理: 采用springmvc注解方式启动,内置http服务器(默认tomcat),所以不需要额外配置Tomcat

package com.xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
 */
@SpringBootApplication
public class Springboot01Application {

    //启动应用
    public static void main(String[] args) {
        SpringApplication.run(Springboot01Application.class, args);
    }

}

  • @SpringBootApplication:Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用;

  • @SpringBootApplication组合注解,兼备了@EnableAutoConfiguration、@Configuration和@ComponentScan 注解的功能。

  • @EnableAutoConfiguration: 启动自动配置机制

  • @ComponentScan: 启动组件扫描。

  • @Configuration: 注册额外的bean或者导入其他配置类。

4.4测试

直接运行启动类Springboot01Application即可,控制台出现如下提示,说明启动成功。

com.xxx.Springboot01Application: Started Springboot01Application in 1.909 seconds (JVM running for 3.553)

然后我们可以添加controller继续测试

@RestController
public class HelloController {

    @RequestMapping("/")
    public String home() {
        return "第一个SpringBoot!!!";
    }

}

通过浏览器访问下面地址:http://127.0.0.1:8080/

浏览器页面出现 “第一个SpringBoot!!!” ,说明搭建成功!

注意:默认端口就是8080。

4.5配置文件

SpringBoot使用一个全局的配置文件,配置文件名是固定的,因为SpringBoot遵从约定大于配置规则。

配置文件位于resources文件夹下,配置文件支持2种风格:

  • application.properties
  • application.yml

4.5.1application.properties

SpringBoot会默认扫描这个配置文件,这里的命名只能是application,因为SpringBoot遵从约定大于配置规则。

application.properties示例:

server.port=8080
server.servlet.context-path=/

4.5.2YAML语法

基本语法:

  • k:(空格)v:表示一对键值对(空格必须有)
  • 以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的
  • 属性和值也是大小写敏感
  • 值中的字符串默认不用加上单引号或者双引号

application.yml示例:

server:
  port: 8080
  servlet-path: /

(ps:其实SpringBoot底层会把application.yml文件解析为application.properties)

4.6@Value读取配置文件

案例:

@Controller
//默认获取的是application.properties中的值
//如果不是,则需要加上@PropertySource注解,且指定配置文件名称
//@PropertySource(value = "classpath:application.properties") //可以不配置
//@PropertySource(value = "classpath:user.properties")        //必须配置
public class TestController {

    //方式一
    @Autowired
    private Environment environment;

    //方式二
    @Value("${server.port}")
    private String port;

    @GetMapping("test")
    @ResponseBody
    public void test() {
        System.out.println("获取配置文件中的值:" + environment.getProperty("server.port"));
        System.out.println("获取配置文件中的值port:" + port);
    }

}

4.7返回json格式数据

springboot返回json格式数据

4.7.1返回对象数据

增加POJO:

public class Student {
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

}

}

UserController

@RestController
public class UserController {
    @RequestMapping("/getStudent")
    public Student getStudent(){
        return new Student("张三",44);
    }
}

在浏览器访问:http://127.0.0.1:8080/getStudent,即可以看到返回的json数据
在这里插入图片描述

4.7.2返回数组类型

在TestController增加方法getStudents():

@RequestMapping("/getStudents")
public List<Student> getStudents() {
    List students=new ArrayList();

    students.add(new Student("张三",12));
    students.add(new Student("张三2",13));
    students.add(new Student("张三3",22));
    students.add(new Student("张三4",33));
    students.add(new Student("张三5",44));

    return students;
}

在浏览器访问:http://127.0.0.1:8080/getStudents,即可以看到返回的数组数据:
在这里插入图片描述

4.7.3返回HashMap数据

增加方法:

@RestController
public class HashMapController {
    @RequestMapping("/getStudentMap")
    public Map getStudentMap() {
        Map map = new HashMap();
        List students=new ArrayList();
        students.add(new Student("张三",12));
        students.add(new Student("张三2",13));
        students.add(new Student("张三3",22));
        students.add(new Student("张三4",33));
        students.add(new Student("张三5",44));

        map.put("retcode",1);
        map.put("students",students);
        return map;
    }
}

在浏览器访问:http://127.0.0.1:8080/getStudentMap
在这里插入图片描述

4.8springboot使用静态资源

在 Spring Boot 中,默认情况下,一共有5个位置可以放静态资源,五个路径分别是如下5个:.

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/:当前项目的根路径

优先级别是从上往下,即如果在以上5个目录出现相同的文件,会按照这个优先级别来显示。

在资源文件resources目录下建立如下四个目录:
在这里插入图片描述
我们项目的静态资源存放在 static下面。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十三豆啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值