SpringBoot快速入门

Posted g-cl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot快速入门相关的知识,希望对你有一定的参考价值。

一、SpringBoot简介
 
1.1 原有Spring优缺点分析
1.1.1 Spring的优点分析
 
Spring是Java企业版(Java Enterprise Edition,JEE,也称J2EE)的轻量级代替品。无需开发重量级的Enterprise
JavaBean(EJB),Spring为企业级Java开发提供了一种相对简单的方法,通过依赖注入和面向切面编程,用简单
的Java对象(Plain Old Java Object,POJO)实现了EJB的功能。
 
1.1.2 Spring的缺点分析
 
虽然Spring的组件代码是轻量级的,但它的配置却是重量级的。一开始,Spring用XML配置,而且是很多XML配
置。Spring 2.5引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式XML配置。Spring 3.0引入
了基于Java的配置,这是一种类型安全的可重构配置方式,可以代替XML。
所有这些配置都代表了开发时的损耗。因为在思考Spring特性配置和解决业务问题之间需要进行思维切换,所以编
写配置挤占了编写应用程序逻辑的时间。和所有框架一样,Spring实用,但与此同时它要求的回报也不少。
除此之外,项目的依赖管理也是一件耗时耗力的事情。在环境搭建时,需要分析要导入哪些库的坐标,而且还需要
分析导入与之有依赖关系的其他库的坐标,一旦选错了依赖的版本,随之而来的不兼容问题就会严重阻碍项目的开
发进度。
 
1.2 SpringBoot的概述
1.2.1 SpringBoot解决上述Spring的缺点
 
SpringBoot对上述Spring的缺点进行的改善和优化,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑
业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的效率,一定程度上缩短
了项目周期。1.2.2 SpringBoot的特点
为基于Spring的开发提供更快的入门体验
开箱即用,没有代码生成,也无需XML配置。同时也可以修改默认值来满足特定的需求
提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等
SpringBoot不是对Spring功能上的增强,而是提供了一种快速使用Spring的方式
 
1.2.3 SpringBoot的核心功能
 
  • 起步依赖
    起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依
    赖,这些东西加在一起即支持某项功能。
    简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。
     
  • 自动配置
    Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定
    Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。

 

二、基础项目搭建

搭建一个maven项目,之后再其中的 pom.xml 中添加SpringBoot的起步依赖

SpringBoot要求,项目要继承SpringBoot的起步依赖spring-boot-starter-parent
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
 
SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

上面看到的spring-boot-starter-xxx就是SpringBoot的起步依赖。SpringBoot通过提供众多起步依赖降低项目依赖的复杂度。起步依赖本质上是一个Maven项目对象模型,定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。很多起步依赖的命名都暗示了他们提供的某种或某类功能

我们还需要配置引导类,如下

技术图片

 

 

package pojo;

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

@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }
}

 

这样就已经配制好SpringBoot了,相对于Spring简单的多,在SpringBoot中有内部默认为8080端口号的服务器,运行一下
 
  .   ____          _            __ _ _
 /\\ / ___‘_ __ _ _(_)_ __  __ _    ( ( )\\___ | ‘_ | ‘_| | ‘_ / _` |     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  ‘  |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

2020-02-06 14:34:40.487  INFO 517816 --- [  restartedMain] pojo.MySpringBootApplication             : Starting MySpringBootApplication on LAPTOP-13GS0P5U with PID 517816 (C:UsersgaochIdeaProjectsquick	argetclasses started by gaoch in C:UsersgaochIdeaProjectsquick)
2020-02-06 14:34:40.489  INFO 517816 --- [  restartedMain] pojo.MySpringBootApplication             : No active profile set, falling back to default profiles: default
2020-02-06 14:34:40.712  INFO 517816 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@593192bf: startup date [Thu Feb 06 14:34:40 CST 2020]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (file:/C:/Users/gaoch/.m2/repository/org/springframework/spring-core/5.0.5.RELEASE/spring-core-5.0.5.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2020-02-06 14:34:47.403  INFO 517816 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-02-06 14:34:47.467  INFO 517816 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-06 14:34:47.468  INFO 517816 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
2020-02-06 14:34:47.492  INFO 517816 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:JAVAjdk-10.0.1in;C:WINDOWSSunJavain;C:WINDOWSsystem32;C:WINDOWS;D:JAVAjdk-10.0.1in;C:UsersgaochAppDataLocalProgramsPythonPython36-32Scripts;C:UsersgaochAppDataLocalProgramsPythonPython36-32;D:Scripts;D:;C:Program Files (x86)InteliCLS Client;C:Program FilesInteliCLS Client;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShellv1.0;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program FilesIntelWiFiin;C:Program FilesCommon FilesIntelWirelessCommon;C:Program Files (x86)IntelIntel(R) Management Engine ComponentsDAL;C:Program FilesIntelIntel(R) Management Engine ComponentsDAL;C:Program Files (x86)IntelIntel(R) Management Engine ComponentsIPT;C:Program FilesIntelIntel(R) Management Engine ComponentsIPT;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:WINDOWSSystem32OpenSSH;C:Program FilesGitcmd;C:Program Filesdotnet;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:Program FilesPuTTY;D:apache-maven-3.5.2in;D:mavenapache-maven-3.5.2in;D:androidandroid-sdk-windows;C:Program FilesMicrosoft SQL ServerClient SDKODBC130ToolsBinn;C:Program Files (x86)Microsoft SQL Server130ToolsBinn;C:Program FilesMicrosoft SQL Server130DTSBinn;C:Program Files (x86)Microsoft SQL Server150DTSBinn;C:Program Files (x86)GtkSharp2.12in;D:pythonScripts;D:python;C:UsersgaochAppDataLocalProgramsPythonPython36-32Scripts;C:UsersgaochAppDataLocalProgramsPythonPython36-32;C:UsersgaochAppDataLocalMicrosoftWindowsApps;;C:Program Files (x86)SSH Communications SecuritySSH Secure Shell;D:ideaIntelliJ IDEA 2018.3.2in;;.]
2020-02-06 14:34:47.883  INFO 517816 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-02-06 14:34:47.883  INFO 517816 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 7184 ms
2020-02-06 14:34:48.322  INFO 517816 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2020-02-06 14:34:48.370  INFO 517816 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘characterEncodingFilter‘ to: [/*]
2020-02-06 14:34:48.370  INFO 517816 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘hiddenHttpMethodFilter‘ to: [/*]
2020-02-06 14:34:48.371  INFO 517816 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘httpPutFormContentFilter‘ to: [/*]
2020-02-06 14:34:48.371  INFO 517816 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘requestContextFilter‘ to: [/*]
2020-02-06 14:34:48.930  INFO 517816 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2020-02-06 14:34:49.573  INFO 517816 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@593192bf: startup date [Thu Feb 06 14:34:40 CST 2020]; root of context hierarchy
2020-02-06 14:34:49.835  INFO 517816 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/quick]}" onto public java.lang.String pojo.controller.QuickStartController.quick()
2020-02-06 14:34:49.842  INFO 517816 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2020-02-06 14:34:49.844  INFO 517816 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2020-02-06 14:34:50.003  INFO 517816 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2020-02-06 14:34:50.004  INFO 517816 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2020-02-06 14:34:50.824  INFO 517816 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-02-06 14:34:50.954  INFO 517816 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2020-02-06 14:34:51.122  INFO 517816 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ‘‘
2020-02-06 14:34:51.139  INFO 517816 --- [  restartedMain] pojo.MySpringBootApplication             : Started MySpringBootApplication in 11.637 seconds (JVM running for 14.557)

在倒数第二行中出现Tomcat started on port(s): 8080 (http) with context path ‘‘

我们在浏览器中出入localhost:8080 

出现一下页面就说明SpringBoot的配置没有任何问题

技术图片

 

下面,我们要实现Controller层方法的实现,需要在引导类的同级或者是子包中创建才有效

 

技术图片

 

package pojo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class QuickStartController {

    @RequestMapping("/quick")
    @ResponseBody
    public String quick() {
        return "SpringBoot test";
    }
}
@ResponseBody :注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。
注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。

我们在启动下服务器,并访问 localhost:8080/quick
技术图片

 


 三、SpringBoot的配置文件


SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.ymlapplication.yaml)进行配置。

SpringBoot默认会从Resources目录下加载application.propertiesapplication.ymlapplication.yaml)文件。
 
并且加载顺序会是.yml 然后是.properties文件的前后顺序,这样,项目的配置会取后值,也就是.properties中配置的值。

 

这里展示一些关于.yml文件的格式,并写入 application.yml 文件中

#普通数据
name: GCL


#对象
person:
  name: zhangsan
  age: 32
  addr: 内蒙古
#或者
#persion: {name: haohao,age: 32,addr: 内蒙古}


#数组
city:
  - beijing
  - shanghai
  - tianjing
  - neimenggu

#或者
#city: [beijing,shanghai,tianjing,neimenggu]


#集合中的元素是对象形式
student:
  - name: zhangsan
    age: 18
    score: 100
  - name: lisi
    age: 18
    score: 100
  - name: wangwu
    age: 18
    score: 100

 

下面演示如何去获取这些值

方法一:


   @Value("${name}")
    private String name;

    @Value("${person.addr}")
    private String addr;

    @Value("${city[0]}")
    private String city;

    @Value("${student[0].score}")
    private Integer score;

package pojo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class QuickStartController {

    @Value("${name}")
    private String name;

    @Value("${person.addr}")
    private String addr;

    @Value("${city[0]}")
    private String city;

    @Value("${student[0].score}")
    private Integer score;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick() {
        return "name:" + name + " " + "addr:" + addr + " " + "city:" + city + " " + "score:" + score;
    }
}
我们可以通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上,执行效果如下技术图片

 

技术图片

 

 

 

 

 

方法二:
通过注解@ConfigurationProperties(prefifix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射。

package pojo.controller;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {

    private String name;
    private Integer age;
    private String addr;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick() {
        ;return "name:" + name + " " + "age" + age + " " + "addr:" + addr;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }
}

 

而配置的属性是需要生生getter和setter方法的,这样就可以通过@ConfigurationProperties注解进行

技术图片

 

四、SpringBoot与整合其他技术 
4.1 SpringBoot整合Mybatis
4.1.1 添加Mybatis的起步依赖与数据库驱动坐标
 
<!--mybatis起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

<!-- mysql连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

4.1.2 添加数据库连接信息 

 

在 application.properties 文件中添加

 

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver 
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test? useUnicode=true&characterEncoding=utf8 
spring.datasource.username=root 
spring.datasource.password=nixiaozi773963

 

4.1.3 创建数据库user表

CREATE DATABASE test;
USE test;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(50) DEFAULT NULL,
    `password` VARCHAR(50) DEFAULT NULL,
    `name` VARCHAR(50) DEFAULT NULL, PRIMARY KEY (`id`) 
) ENGINE=INNODB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; 
-- ---------------------------- -- Records of user -- ---------------------------- 
INSERT INTO `user` VALUES (1, zhangsan, 123, 张三); 
INSERT INTO `user` VALUES (2, lisi, 123, 李四);

4.1.4 创建实体Bean

package pojo.domain;

public class User {
    //主键
    private Long id;
    //用户名
    private String username;
    //密码
    private String password;
    //姓名
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

4.1.5 编写Mapper

package pojo.mapper;

import org.apache.ibatis.annotations.Mapper;
import pojo.domain.User;

import java.util.List;

@Mapper
public interface UserMapper {

    public List<User> queryUserList();

}
注意:@Mapper标记该类是一个mybatismapper接口,可以被spring boot自动扫描到spring上下文中
 
4.1.6 配置Mapper映射文件 

在resourcesmapper加入 UserMapper.xml 配置文件

<?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="pojo.mapper.UserMapper">
    <select id="queryUserList" resultType="user"> select * from user </select>
</mapper>

4.1.7 在application.properties中添加mybatis的信息

#spring集成Mybatis环境
#pojo别名扫描包
mybatis.type-aliases-package=pojo.domain
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

最后,编写测试类

package pojo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import pojo.domain.User;
import pojo.mapper.UserMapper;

import java.util.List;

@Controller
public class MapperController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/queryList")
    @ResponseBody
    public List<User> queryUser() {
        List<User> users = userMapper.queryUserList();
        return users;
    }

}

 

运行成功,如下

技术图片

 

 出现数据就是正确的解析结果 我这里是使用了解析json数据的浏览器插件

 

4.2 SpringBoot整合Junit

4.2.1 添加Junit的起步依赖

<!--测试的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>compile</scope>
        </dependency>
4.2.2编写测试类
 
package pojo.test;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import pojo.MySpringBootApplication;
import pojo.domain.User;
import pojo.mapper.UserMapper;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes= MySpringBootApplication.class)
public class MapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void Test() {
        List<User> users = userMapper.queryUserList();
        for (User user: users
             ) {
            System.out.println(user);
        }

    }

}

 

需要在之前写的User类中吧toString()方法实现了

 

技术图片

 

 

 

 
 
 
 
在关于整合redis与热部署时,导入相应坐标时,不明所以的出现错误,如有大神看到,请多多指点。
技术图片

 

以上是关于SpringBoot快速入门的主要内容,如果未能解决你的问题,请参考以下文章

SpringData 基于SpringBoot快速入门

SpringBoot -- 概述和快速入门快速构建SpringBoot工程

SpringBoot快速入门

Java 微服务 乐优网络商城 day01 源代码 SpringBoot的SpringMVC快速入门

快速入门:创建第一个SpringBoot工程

快速上手SpringBoot盘点盘点入门程序制作的四种方式(有图有代码)