SpringBoot入门介绍

SpringBoot的概念


SpringBoot是Spring公司的一个顶级项目,与Spring Framework是一个级别的。SpringBoot实际上是利用Spring Framework 4自动配置特性完成的。

在编写项目时不需要编写xml文件。到现在,各种主流技术都提供了SpringBoot的启动器。

启动器?Spring框架在项目中的作用经常是整合各种其他技术,让其他技术使用的更加的便捷。SpringBoot的启动器实际上就是一个maven的依赖,一个依赖中包含了相关技术的jar包,还包含了该技术的自动配置,使得以前绝大数xml文件已经不需要再配置了,例如mybaist-config.xml、jdbc.properties、log4j.properties、applicationContext.xml、springmvc.xml等等的配置文件都无需再进行配置。但是还是需要在SpringBoot的配置文件中进行少量的配置。

Spring官方提供的启动器命名规则为** spring-boot-starter-xxx,而如果是第三方技术提供的启动器命名规则是:xxx-spring-boot-starter**

SpringBoot的本质就是Spring Framework,学习SpringBoot就是在学习如何整合其他技术

Springboot特点有哪些?

(1)可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs;
(2)内嵌Tomcat或Jetty等Servlet容器;
(3)提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置;
(4)尽可能自动配置Spring容器;
(5)提供准备好的特性,如指标、健康检查和外部化配置;
(6)绝对没有代码生成,不需要XML配置。

创建springboot工程

 创建一个Controller

 Pox.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: 继承
        如果你的maven项目想成为springboot工程必须继承SpringBoot父依赖
 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wd</groupId>
    <artifactId>SpringBoot-demo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot-demo1</name>
    <description>SpringBoot-demo1</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--web的启动依赖 把spring中常见的jar都集成到该依赖中,集成了springmvc的启动配置类 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.7.8</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

Springboot的配置文件

第一种: properties属性文件

第二种: yml文件

--------------------------------

不管是哪种,他们的名字必须以application开始。

如果两个配置文件同时存在,而且有些内容一样。按照properties的优先级高。如果有些不一样,两个配置文件不一样的会合并在一起。

读取Springboot配置文件中的内容

如何读取springboot配置文件的内容呢?

通过@ConfigurationProperties或者@Value注解。

如:

#自定义的配置信息
student.name=ldh
student.age=15
student.hobby[0]=sing
student.hobby[1]=swing

创建Student的实体类

@Data
@Component //该类对象的创建和销毁都有spring容器来管理
@ConfigurationProperties(prefix = "student")    //读取springboot中的配置内容

public class Student {

private String name;

private Integer age;

private String[] hobby;

private Map<String,Object> map;

}


 

调用 Controller

 

@Autowired//spring容器帮你注入该对象
private Student student;

@GetMapping("/index")
public Student index() {
    System.out.println("====" + student.getAge());
    return student;
}

Profiles文件的介绍

 

 

Springboot注册web三大组件

什么是web的三个组件?

        Servlet和Filter以及Linstener监听器。

为什么要注册这三个组件呢?  

        因为后面springboot有可能要集成第三方框架,而第三方框架的底层可能就依赖于过滤器或者servlet.

如何注册呢?  

        

<1>Servlet类

<2>注册到Tomcat容器web.xml

<1>Servlet类

<2>注册到Tomcat容器web.xml

---------------------------------------------------

现在:都没有web.xml

@Configuration //该类为配置类 xml文件
public class MyConfig {

 @Bean  //理解为配置文件中<bean >
 public ServletRegistrationBean<Servlet> registrationBean(){
     //创建一个Servlet注册器.
      ServletRegistrationBean<Servlet> registrationBean=new ServletRegistrationBean<>();
      registrationBean.setName("my");
      registrationBean.setServlet(new MyServlet());
      registrationBean.addUrlMappings("/my");
      return registrationBean;
 }

}

注册过滤器

@Bean
 public FilterRegistrationBean<Filter> filterRegistrationBean(){
       FilterRegistrationBean<Filter> filterRegistrationBean=new FilterRegistrationBean<>();
       filterRegistrationBean.setName("myfilter");
       filterRegistrationBean.setFilter(new MyFilter());
       filterRegistrationBean.addUrlPatterns("/*");
       return filterRegistrationBean;
 }

 

@Configuration   别忘了这个注解

Springboot自动装配原理:

主函数启东市会宇宁一个包含

@SpringBootApplication的类

 

@SpringBootApplication 中包含   

@EnableAutoConfiguration 

 @EnableAutoConfiguration 开启自动配置的功能

@Import({AutoConfigurationImportSelector.class})

该注解会导入  AutoConfigurationImportSelector 

而这个类加载一些自动装配类,从而完成自动装配的功能.

 

Springboot整合数据源& 集成Druid数据源

数据源: 指的是数据源。即是: springboot框架连接数据库。

(1)引入依赖

<!--加入数据源的启动依赖: springboot启动时会加载对应的自动装配类。-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
 <!--引入数据库连接池druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

(2)配置数据源信息--- application.yml

server:
  port: 8899
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
#  banner:
#    image:
#      location: default.jpeg


 

 

(3)测试

     @Autowired
    private DataSource dataSource;

    @Test
    void test01() throws SQLException {
        System.out.println(dataSource.getConnection());
    }

Springboot整合mybatis

(1)引入mybatis启动依赖类

 <!--引入mybatis的启动依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

(2) 修改配置文件

mybatis:
  mapper-locations: classpath:mapper/*.xml

(3)主启动类加上注解

 (4)测试

------------------------

Springboot整合swagger2.

(1)引入swagger依赖

<dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.7.8</version>
        </dependency>

(2)创建swagger配置类

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//设置api的文档信息
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.wd.springbootdemo1.controller"))
                .build();
        return docket;
    }

    //定义自己接口文档信息
    private ApiInfo apiInfo() {
        Contact DEFAULT_CONTACT = new Contact("胡思乱想DouZi", "http://www.baidu.com", "110@qq.com");
        ApiInfo apiInfo = new ApiInfo("Test在线文档", "这个文档是世界上最牛一个文档", "V1.0", "http://www.jd.com",
                DEFAULT_CONTACT, "甲子信息", "http://www.taobao.com", new ArrayList<VendorExtension>());

        return apiInfo;
    }
}

(3)开启swagger注解

 (4)使用swagger注解

@Api  接口类的注解---接口类上 tag属性
@ApiOperation  接口方法的注解---接口方法上 value:
@ApiImplicitParams( 接口参数的说明
    {
      ApiImplicitParam() //单个参数的说明
    }
)

@ApiModel---- 实体类接口注解
@ApiModelProperty---->实体类属性的说明

Controller书写:

package com.wd.springbootdemo1.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wd.springbootdemo1.dao.PeopleMapper;
import com.wd.springbootdemo1.entity.People;
import com.wd.springbootdemo1.entity.Student;
import com.wd.springbootdemo1.until.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DouZi
 * @Blog areone.top
 */
@RestController
@Api(tags = "Hello接口类")
public class HelloController {
    @Autowired
    private PeopleMapper peopleMapper;

    @GetMapping("/hello")
    public Map<String, Object> hello() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "DouZi");
        map.put("age", 21);
        return map;
    }

    @Autowired
    private Student student;

    @GetMapping("/index")
    public Student index() {
        System.out.println("====" + student.getAge());
        return student;
    }

    @GetMapping("/getOne")
    @ApiOperation(value = "获取单个用户信息")
    @ApiImplicitParam(value = "ID号", name = "id")
    CommonResult findOne(Integer id) {
        People byID = peopleMapper.findByID(id);
        return new CommonResult(200, "成功获取到啦", byID);
    }

    @GetMapping("/findAll")
    @ApiOperation(value = "获取全部用户信息")
    CommonResult findALl() {
        PageHelper.startPage(1, 3);
        List<People> list = peopleMapper.findAll();
        PageInfo<People> pageInfo = new PageInfo<>(list);
        List<People> list1 = pageInfo.getList();
        return new CommonResult(200, "获取成功啦~", list1);
    }
    @PostMapping("/delOne")
    @ApiOperation(value = "删除某个用户信息")
    @ApiImplicitParam(value = "需要删除用户的ID",name = "id")
    CommonResult delOne(Integer id) {
        int i = peopleMapper.delOne(id);
        return new CommonResult(200, "删除成功啦~", i);
    }

    @PostMapping("/addOne")
    @ApiOperation(value = "增加某个用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户的name",name = "name"),
            @ApiImplicitParam(value = "用户的age",name = "age") ,
            @ApiImplicitParam(value = "用户的password",name = "password")
    })
    CommonResult addOne(String name,String password,Integer age) {
        int i = peopleMapper.addOne(name,password,age);
        return new CommonResult(200, "成功啦~", i);
    }
    @PostMapping("/upOne")
    @ApiOperation(value = "更新某个用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "需要更新用户的ID",name = "id"),
            @ApiImplicitParam(value = "需要更新用户的age",name = "age") ,
            @ApiImplicitParam(value = "需要更新用户的password",name = "password")
    })
    CommonResult upOne(Integer id,Integer age,String password) {
        int i = peopleMapper.upOne(id,age,password);
        return new CommonResult(200, "更新成功啦~", i);
    }

}

 (5)访问

第一种: localhost:自己的端口号/doc.html

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值