springBoot快速上手

spring boot和spring mvc的关系

spring boot是spring mvc的升级版

spring boot的特点

1 化繁为简,2下一代框架,3微服务的入门级微框架(spring cloud的基础)

创建spring boot项目

1:idea开发工具
file-new project-


image.png

选择需要的相关组件


image.png

2:访问https://start.spring.io/创建,下载zip包解压导入

image.png

项目的结构

image.png

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>
    <!--spring boot的parent-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--项目的属性,版本号,打包方式等等-->
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
<!--Java的版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--作为web项目必须引入的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!--spring单元测试的模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
 </dependencies>
<!--构建maven的一个插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

spring boot项目的启动类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*每个项目只有一个这样的注解*/
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

启动项目访问127.0.0.1:8080


image.png

image.png

什么都没有写报404错误

新建一个测试类

@RestController
/*@RestController是一个组合注解,放回json字符串*/
public class OneTest {
/*路径为start,请求方式get*/
    @RequestMapping(value = "/start",method =RequestMethod.GET)
    public String start(){
        return "helllwork";
    }
    @RequestMapping(value = "/begin",method =RequestMethod.GET)
    public String begin(){
        return "index";
    }
}

访问

image.png

启动项目的方式

1使用idea工具(个人电脑)
2打包jar包或是war包(适用于服务器)
3使用maven命令来启动(都行)

项目配置

image.png

建议将默认application.properties文件改为application.yml


image.png

自定义配置

server:
设置端口号
  port: 8082
say: 123456

测试类

public class OneTest {
    @Value("${say}")
    private String say;
    /*路径为start,请求方式get*/
    @RequestMapping(value = "/start",method =RequestMethod.GET)
    public String start(){
        return "helllwork"+say;
    }

显示结果:


image.png

在配置里面使用配置

say: 123456
name: maomao
person: "name: ${name},say: ${say}"

java类

public class OneTest {
    @Value("${say}")
    private String say;
    @Value("${person}")
    private String person;
    /*路径为start,请求方式get*/
    @RequestMapping(value = "/start",method =RequestMethod.GET)
    public String start(){
        return person;
    }
image.png

另一种使用方式

person:
  say: 123456
  name: maomao
  kg: 70

创建一个实体类

@Component
@ConfigurationProperties(prefix = "person")
/*读取配置文件引用person*/
public class Person {
    private String name;
    private String say;

    private String kg;

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

测试类

public class OneTest {

    @Autowired
    private Person person;
    /*路径为start,请求方式get*/
    @RequestMapping(value = "/start",method =RequestMethod.GET)
    public String start(){
        return person.getKg()+person.getName()+person.getSay();
    }
image.png

切换配置环境

image.png

控制器的使用Controller的使用

@Controller(处请求理http,需要配合模板使用,了解就行,现在都前后端分离)
@RestController(Spring4之后新加的注解,原来返回json需要@ResponseBody配合@Controller )
@RequestMapping(配置url映射)

可以为整个类设定一个url,value可以设为一个集合支持多个url,如果method 省约,所有请求都能访问到(不推荐,不安全)
@RequestMapping(value = {"/start","/hi"},method =RequestMethod.GET)
(组合注解@GetMapping,@PostMapping等等)

获取url中的数据

@PathVariable(获取url中的数据)
@RequestParam(获取请求参数的指)
@GetMapping(组合注解)
@PathVariable:

public class OneTest {

    @Autowired
    private Person person;
    /*路径为start,请求方式get*/
    @RequestMapping(value = "/start/{id}"/*位置可以随意*/,method = RequestMethod.GET)
    public String start(@PathVariable("id") Integer myid){
        return myid.toString();
    }

返回结果


image.png
@RequestParam
/*
  (@RequestParam(value = "id",required = false/*不是必须传*/,defaultValue = "81"/*默认值*/)
*/

 @RequestMapping(value = "/start",method = RequestMethod.POST)
    public String start(@RequestParam("id") Integer myid){
        return myid.toString();
    }
image.png

spring boot数据库操作

Spring-data-Jpa
JPA(java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有hibernate,TopLInk等。

<!--使用数据库,需要添加两个组件,一个数据库的驱动,另一个spring data jpa-->
       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

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

配饰数据库

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
   时区报错加的后缀
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: create
    show-sql: true

编写实体类

@Entity
public class Student {
    @Id
    /*自增*/
    @GeneratedValue
    private Integer id;
    private String name;
    private Integer age;
    private Integer score;

    public Student() {
        
    }
get和set方法。。。。。。
}

运行控制台消息


image.png

数据库显示

image.png
书写Repository层(dao层)
package com.example.demo.Repository;

import com.example.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository <Student,Integer> {
    /*后面的泛型第一个是操作的类,第二个为主键的类型*/
}
直接在Controller层调用Repository
@RestController
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public List<Student> getStudentList() {
        return  studentRepository.findAll();
    }
}

显示结果


image.png

自己扩展方法

public interface StudentRepository extends JpaRepository <Student,Integer> {
    /*后面的泛型第一个是操作的类,第二个为主键的类型*/
    public List<Student> findByAge(Integer age);
}
Controller
   @RequestMapping(value = "listOne",method = RequestMethod.GET)
    public List<Student> getByAgeList(@RequestParam ("age") Integer age) {
        return  studentRepository.findByAge(age);
    }

结果


image.png

事务管理

import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    @Transactional
    事务管理的注解
    public void insertTow() {
        Student a=new Student();
        a.setId(5);
        a.setAge(13);
        a.setName("sda");
        Student b=new Student();
        b.setId(3);
        b.setAge(14);
        b.setName("hds");
        studentRepository.save(a);
        studentRepository.save(b);
    }

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容