码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot快速入门

时间:2020-02-06 20:03:30      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:erp   this   集合   rds   android   space   class   scom   git   

一、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:\Users\gaoch\IdeaProjects\quick\target\classes started by gaoch in C:\Users\gaoch\IdeaProjects\quick)
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:\JAVA\jdk-10.0.1\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:\JAVA\jdk-10.0.1\bin;C:\Users\gaoch\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\gaoch\AppData\Local\Programs\Python\Python36-32\;D:\Scripts\;D:\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\PuTTY\;D:\apache-maven-3.5.2\bin;D:\maven\apache-maven-3.5.2\bin;D:\Android\android-sdk-windows;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn\;C:\Program Files (x86)\GtkSharp\2.12\bin;D:\python\Scripts\;D:\python\;C:\Users\gaoch\AppData\Local\Programs\Python\Python36-32\Scripts\;C:\Users\gaoch\AppData\Local\Programs\Python\Python36-32\;C:\Users\gaoch\AppData\Local\Microsoft\WindowsApps;;C:\Program Files (x86)\SSH Communications Security\SSH Secure Shell;D:\idea\IntelliJ IDEA 2018.3.2\bin;;.]
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映射文件 

在resources\mapper加入 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快速入门

标签:erp   this   集合   rds   android   space   class   scom   git   

原文地址:https://www.cnblogs.com/g-cl/p/12269939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!