Springboot经典入门——踏进去的第一脚

随着微服务的遍地开花,SpringBoot成了框架中的一颗耀眼明星。在还没有接触SpringBoot的一段时间内,一直认为Spring已经是和轻量级的框架, 即使编程过程中需要配置的内容比较繁琐,但也是使用一段时间后才会有的感触。就像ecplise的出现扼杀了netBeans,IDEA的出现也撼动了ecplise的霸主地位。新的事物或者方式方法出现体现了行业的活力,也使从业者能不断注入新鲜的血液,更能适行业的发展。以下是学习的过程中,其实写博客更像是一种学习笔记吧。

Spring是Java企业版(Java Enterprise Edition,JEE,也称J2EE)的轻量级代替品。无需开发重量级的Enterprise
JavaBean(EJB),Spring为企业级Java开发提供了一种相对简单的方法,通过依赖注入和面向切面编程,用简单
的Java对象(Plain Old Java Object,POJO)实现了EJB的功能。(以上内容摘自《Spring Boot 实战》)

  • 1.1.2 Spring的缺点分析

虽然Spring的组件代码是轻量级的,但它的配置却是重量级的。一开始,Spring用XML配置,而且是很多XML配置。Spring 2.5引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式XML配置。Spring 3.0引入了基于Java的配置,这是一种类型安全的可重构配置方式,可以代替XML。所有这些配置都代表了开发时的损耗。因为在思考Spring特性配置和解决业务问题之间需要进行思维切换,所以编写配置挤占了编写应用程序逻辑的时间。和所有框架一样,Spring实用,但与此同时它要求的回报也不少。除此之外,项目的依赖管理也是一件耗时耗力的事情。在环境搭建时,需要分析要导入哪些库的坐标,而且还需要分析导入与之有依赖关系的其他库的坐标,一旦选错了依赖的版本,随之而来的不兼容问题就会严重阻碍项目的开发进度。

(以上内容摘自《Spring Boot 实战》)

  • 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自动完成的。

在有了初步了解之后,是不是已经开始对于Springboot的开发已经跃跃欲试了。下面开始第一个入门案例。

开发环境:IDEA +JDK1.8

1)新建Maven项目pom.xml文件配置主要包括两个步骤:

  • 1.继承SpringBoot的起步依赖spring-boot-starter-parent
  • 2.集成SpringMVC进行Controller的开发,导入web的启动依赖
<?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>

    <groupId>cn.springboot</groupId>
    <artifactId>SpringBootDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--1、继承SpringBoot的起步依赖spring-boot-starter-parent-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    <!--2、集成SpringMVC进行Controller的开发,导入web的启动依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

2)新建SpringBoot引导类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * SpringBoot引导类
 */
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String [] arg){
        SpringApplication.run(MySpringBootApplication.class);
    }
}

注:未引用注解@SpringBootApplication会报错:Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean 

3)新建Controller类

package cn.helloSpringBoot.co.helloSpringBoot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class QuickStartController {
    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "Hello SpringBoot";
    }
}

4)效果展示:

D:\develop\JDK1.8\bin\java.exe -javaagent:D:\IDEA\lib\idea_rt.jar=63388:D:\IDEA\bin -Dfile.encoding=UTF-8 -classpath D:\develop\JDK1.8\jre\lib\charsets.jar;D:\develop\JDK1.8\jre\lib\deploy.jar;D:\develop\JDK1.8\jre\lib\ext\access-bridge-64.jar;D:\develop\JDK1.8\jre\lib\ext\cldrdata.jar;D:\develop\JDK1.8\jre\lib\ext\dnsns.jar;D:\develop\JDK1.8\jre\lib\ext\jaccess.jar;D:\develop\JDK1.8\jre\lib\ext\jfxrt.jar;D:\develop\JDK1.8\jre\lib\ext\localedata.jar;D:\develop\JDK1.8\jre\lib\ext\nashorn.jar;D:\develop\JDK1.8\jre\lib\ext\sunec.jar;D:\develop\JDK1.8\jre\lib\ext\sunjce_provider.jar;D:\develop\JDK1.8\jre\lib\ext\sunmscapi.jar;D:\develop\JDK1.8\jre\lib\ext\sunpkcs11.jar;D:\develop\JDK1.8\jre\lib\ext\zipfs.jar;D:\develop\JDK1.8\jre\lib\javaws.jar;D:\develop\JDK1.8\jre\lib\jce.jar;D:\develop\JDK1.8\jre\lib\jfr.jar;D:\develop\JDK1.8\jre\lib\jfxswt.jar;D:\develop\JDK1.8\jre\lib\jsse.jar;D:\develop\JDK1.8\jre\lib\management-agent.jar;D:\develop\JDK1.8\jre\lib\plugin.jar;D:\develop\JDK1.8\jre\lib\resources.jar;D:\develop\JDK1.8\jre\lib\rt.jar;D:\SpringBootDemo\target\classes;D:\repository\repository\org\springframework\boot\spring-boot-starter-web\2.0.1.RELEASE\spring-boot-starter-web-2.0.1.RELEASE.jar;D:\repository\repository\org\springframework\boot\spring-boot-starter\2.0.1.RELEASE\spring-boot-starter-2.0.1.RELEASE.jar;D:\repository\repository\org\springframework\boot\spring-boot\2.0.1.RELEASE\spring-boot-2.0.1.RELEASE.jar;D:\repository\repository\org\springframework\boot\spring-boot-autoconfigure\2.0.1.RELEASE\spring-boot-autoconfigure-2.0.1.RELEASE.jar;D:\repository\repository\org\springframework\boot\spring-boot-starter-logging\2.0.1.RELEASE\spring-boot-starter-logging-2.0.1.RELEASE.jar;D:\repository\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\repository\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\repository\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;D:\repository\repository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;D:\repository\repository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;D:\repository\repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;D:\repository\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;D:\repository\repository\org\springframework\spring-core\5.0.5.RELEASE\spring-core-5.0.5.RELEASE.jar;D:\repository\repository\org\springframework\spring-jcl\5.0.5.RELEASE\spring-jcl-5.0.5.RELEASE.jar;D:\repository\repository\org\yaml\snakeyaml\1.19\snakeyaml-1.19.jar;D:\repository\repository\org\springframework\boot\spring-boot-starter-json\2.0.1.RELEASE\spring-boot-starter-json-2.0.1.RELEASE.jar;D:\repository\repository\com\fasterxml\jackson\core\jackson-databind\2.9.5\jackson-databind-2.9.5.jar;D:\repository\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;D:\repository\repository\com\fasterxml\jackson\core\jackson-core\2.9.5\jackson-core-2.9.5.jar;D:\repository\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.5\jackson-datatype-jdk8-2.9.5.jar;D:\repository\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.5\jackson-datatype-jsr310-2.9.5.jar;D:\repository\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.5\jackson-module-parameter-names-2.9.5.jar;D:\repository\repository\org\springframework\boot\spring-boot-starter-tomcat\2.0.1.RELEASE\spring-boot-starter-tomcat-2.0.1.RELEASE.jar;D:\repository\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.29\tomcat-embed-core-8.5.29.jar;D:\repository\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.29\tomcat-embed-el-8.5.29.jar;D:\repository\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.29\tomcat-embed-websocket-8.5.29.jar;D:\repository\repository\org\hibernate\validator\hibernate-validator\6.0.9.Final\hibernate-validator-6.0.9.Final.jar;D:\repository\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;D:\repository\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;D:\repository\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;D:\repository\repository\org\springframework\spring-web\5.0.5.RELEASE\spring-web-5.0.5.RELEASE.jar;D:\repository\repository\org\springframework\spring-beans\5.0.5.RELEASE\spring-beans-5.0.5.RELEASE.jar;D:\repository\repository\org\springframework\spring-webmvc\5.0.5.RELEASE\spring-webmvc-5.0.5.RELEASE.jar;D:\repository\repository\org\springframework\spring-aop\5.0.5.RELEASE\spring-aop-5.0.5.RELEASE.jar;D:\repository\repository\org\springframework\spring-context\5.0.5.RELEASE\spring-context-5.0.5.RELEASE.jar;D:\repository\repository\org\springframework\spring-expression\5.0.5.RELEASE\spring-expression-5.0.5.RELEASE.jar cn.helloSpringBoot.MySpringBootApplication

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

2019-06-09 19:53:13.029  INFO 7752 --- [           main] c.h.MySpringBootApplication              : Starting MySpringBootApplication on USER-20160313BA with PID 7752 (D:\SpringBootDemo\target\classes started by Administrator in D:\SpringBootDemo)
2019-06-09 19:53:13.037  INFO 7752 --- [           main] c.h.MySpringBootApplication              : No active profile set, falling back to default profiles: default
2019-06-09 19:53:13.199  INFO 7752 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@50a7bc6e: startup date [Sun Jun 09 19:53:13 CST 2019]; root of context hierarchy
2019-06-09 19:53:16.439 ERROR 7752 --- [           main] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.1.33] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2019-06-09 19:53:16.625  INFO 7752 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-06-09 19:53:16.661 ERROR 7752 --- [           main] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.1.33] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2019-06-09 19:53:16.681  INFO 7752 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-06-09 19:53:16.682  INFO 7752 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
2019-06-09 19:53:16.700 ERROR 7752 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.1.33] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2019-06-09 19:53:16.973  INFO 7752 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-06-09 19:53:16.973  INFO 7752 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3781 ms
2019-06-09 19:53:17.246  INFO 7752 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2019-06-09 19:53:17.255  INFO 7752 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-06-09 19:53:17.255  INFO 7752 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-06-09 19:53:17.255  INFO 7752 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-06-09 19:53:17.255  INFO 7752 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-06-09 19:53:17.521  INFO 7752 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-06-09 19:53:17.998  INFO 7752 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@50a7bc6e: startup date [Sun Jun 09 19:53:13 CST 2019]; root of context hierarchy
2019-06-09 19:53:18.137  INFO 7752 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/quick]}" onto public java.lang.String cn.helloSpringBoot.co.helloSpringBoot.controller.QuickStartController.quick()
2019-06-09 19:53:18.146  INFO 7752 --- [           main] 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)
2019-06-09 19:53:18.148  INFO 7752 --- [           main] 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)
2019-06-09 19:53:18.198  INFO 7752 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-06-09 19:53:18.199  INFO 7752 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-06-09 19:53:18.577  INFO 7752 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-06-09 19:53:18.662  INFO 7752 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-06-09 19:53:18.670  INFO 7752 --- [           main] c.h.MySpringBootApplication              : Started MySpringBootApplication in 6.508 seconds (JVM running for 7.514)
2019-06-09 19:53:44.903 ERROR 7752 --- [nio-8080-exec-1] o.a.catalina.core.AprLifecycleListener   : An incompatible version [1.1.33] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2019-06-09 19:53:44.923  INFO 7752 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2019-06-09 19:53:44.923  INFO 7752 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2019-06-09 19:53:44.970  INFO 7752 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 46 ms

从启动信息中"o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''可以看出SpringBoot内嵌的TomCat,默认启动端口为8080,看下访问效果:

不得不care的两个点:

  • 1.在入门案例中,起步依赖配置了spring-boot-starter-parent 的parent。而在实际开发中,通常我们会有自己的父类项目。如果都采用这种配置的话,就会产生jar包冲突的问题,不过spring官方也给了一种变通的方法:

在父类项目中加上声明:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

在子类项目中引入父类依赖修改为如下,问题就迎刃而解了。

<parent>
     <groupId>cn.com</groupId>
     <artifactId>parent</artifactId>
     <version>0.1-SNAPSHOT</version>
</parent>
  •  2.如果修改默认端口:在案例,我们启动项目时,会启动一个端口为8080的tomcat。那么如何修改这个默认端口呢?方式有很多种,梳理下常用的三种:
  • 1)在src / main / resources下创建application.properties文件,并在其中定义server.port属性:
server.port=9090
  • 2)在src / main / resources下创建application.yml文件,并在其中定义server.port属性:
server:
  #端口号
  port: 8888
  #项目名,如果不设定,默认是 /
  context-path: /Demo
  • 3)命令行指定端口:不过这种方式会覆盖掉其他方式指定的端口
java -Dserver.port = 9090 -jar Demo.jar

java -jar Demo.jar -server.port = 9090

 在实际的编码过程中配置文件应该是最多选择的。而且不用考虑怎么加载配置文件,如果不存在配置文件就不会加载,存在就进行加载。

以上就是SpringBoot的入门案例, 简单高效。不过但是对于具体的实现机制的话还需要好好分析下。

文件列表:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值