美文网首页
【SpringBoot学习】01. 第一个应用

【SpringBoot学习】01. 第一个应用

作者: _水杉 | 来源:发表于2019-04-10 17:23 被阅读0次

    版本申明

    这里说一下我本地环境的版本信息,免得读者做demo的时候可能和文章中的结果不一致。

    C:\Users\xu>mvn -version
    Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T15:58:13+08:00)
    Maven home: C:\develop\maven\apache-maven-3.5.2\bin\..
    Java version: 1.8.0_151, vendor: Oracle Corporation
    Java home: C:\develop\jdk\jdk1.8\jre
    Default locale: zh_CN, platform encoding: GBK
    OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
    
    C:\Users\xu>java -version
    java version "1.8.0_151"
    Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
    Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)
    

    项目地址 https://gitee.com/better-code/SpringBoot-Example/springboot01


    编写pom.xml

    添加 parent

    <?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>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.2.RELEASE</version>
        </parent>
        
        <groupId>com.example</groupId>
        <artifactId>springboot01</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboot01</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    </project>
    

    这里主要关注 parent 元素。
    parent是父母的意思,在pom.xml定义一个parent,就相当于给项目认了一个“爸爸”。
    “认爸爸”当然是有好处的,能够免费使用“爸爸”拥有的一些东西。
    那么我们项目的“爸爸”——SpringBoot有哪些好处呢?

    spring-boot-starter-parent
    它是一个特殊的starter,提供了有用的Maven默认设置。
    同时,它也提供一个 dependency-management 节点,这样对于期望(”blessed“)的依赖就可以省略version标记了。

    这些官样文字都是虚的,看得懂当然好,看不懂也没关系。真正体会最好,正所谓道可道非常道。

    添加依赖 dependency

    <dependencies>
        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    

    看,要是没认spring-boot-starter-parent做“爸爸”之前,dependency 元素里的version 标签都是必须写明白的
    现在这些活儿爸爸——spring-boot-starter-parent都帮忙做了,这里就能省略了。

    Spring Boot提供很多"Starters",用来简化添加jars到classpath的操作。
    spring-boot-starter-parent,其他”Starters“(如spring-boot-starter-web)只简单提供开发特定类型应用所需的依赖。
    看没,除了spring-boot-starter-web这个好处外,还有其他好处呢,好处大大的 _

    spring-boot-starter-web 究竟是做什么的呢?
    看下面,在没有引入任何依赖时,执行 mvn dependency:tree 命令查看依赖树

    D:\liuchuanwei_study\spring\spring-boot\SpringBoot-Example\springboot01>mvn dependency:tree
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building springboot01 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-dependency-plugin:3.1.1:tree (default-cli) @ springboot01 ---
    [INFO] com.example:springboot01:jar:0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.666 s
    [INFO] Finished at: 2019-04-10T16:12:45+08:00
    [INFO] Final Memory: 22M/227M
    [INFO] ------------------------------------------------------------------------
    

    引入spring-boot-starter-web 之后,再执行 mvn dependency:tree 命令查看依赖树

    D:\liuchuanwei_study\spring\spring-boot\SpringBoot-Example\springboot01>mvn dependency:tree
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building springboot01 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-dependency-plugin:3.1.1:tree (default-cli) @ springboot01 ---
    [INFO] com.example:springboot01:jar:0.0.1-SNAPSHOT
    [INFO] \- org.springframework.boot:spring-boot-starter-web:jar:2.1.2.RELEASE:compile
    [INFO]    +- org.springframework.boot:spring-boot-starter:jar:2.1.2.RELEASE:compile
    [INFO]    |  +- org.springframework.boot:spring-boot:jar:2.1.2.RELEASE:compile
    [INFO]    |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.1.2.RELEASE:compile
    [INFO]    |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.1.2.RELEASE:compile
    [INFO]    |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
    [INFO]    |  |  |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
    [INFO]    |  |  |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
    [INFO]    |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.11.1:compile
    [INFO]    |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.11.1:compile
    [INFO]    |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.25:compile
    [INFO]    |  +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
    [INFO]    |  +- org.springframework:spring-core:jar:5.1.4.RELEASE:compile
    [INFO]    |  |  \- org.springframework:spring-jcl:jar:5.1.4.RELEASE:compile
    [INFO]    |  \- org.yaml:snakeyaml:jar:1.23:runtime
    [INFO]    +- org.springframework.boot:spring-boot-starter-json:jar:2.1.2.RELEASE:compile
    [INFO]    |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.8:compile
    [INFO]    |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
    [INFO]    |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.9.8:compile
    [INFO]    |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.8:compile
    [INFO]    |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.8:compile
    [INFO]    |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.9.8:compile
    [INFO]    +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.1.2.RELEASE:compile
    [INFO]    |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.14:compile
    [INFO]    |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.14:compile
    [INFO]    |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.14:compile
    [INFO]    +- org.hibernate.validator:hibernate-validator:jar:6.0.14.Final:compile
    [INFO]    |  +- javax.validation:validation-api:jar:2.0.1.Final:compile
    [INFO]    |  +- org.jboss.logging:jboss-logging:jar:3.3.2.Final:compile
    [INFO]    |  \- com.fasterxml:classmate:jar:1.4.0:compile
    [INFO]    +- org.springframework:spring-web:jar:5.1.4.RELEASE:compile
    [INFO]    |  \- org.springframework:spring-beans:jar:5.1.4.RELEASE:compile
    [INFO]    \- org.springframework:spring-webmvc:jar:5.1.4.RELEASE:compile
    [INFO]       +- org.springframework:spring-aop:jar:5.1.4.RELEASE:compile
    [INFO]       +- org.springframework:spring-context:jar:5.1.4.RELEASE:compile
    [INFO]       \- org.springframework:spring-expression:jar:5.1.4.RELEASE:compile
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 1.886 s
    [INFO] Finished at: 2019-04-10T16:13:02+08:00
    [INFO] Final Memory: 24M/228M
    [INFO] ------------------------------------------------------------------------
    

    看见没,引入一个spring-boot-starter-web,就相当于引入了上面这一树的依赖。


    编写代码

    @RestController
    @EnableAutoConfiguration
    public class Example {
    
        @RequestMapping("/")
        public String home() {
            return "Hello World !";
        }
    
        public static void main(String[] args) {
            SpringApplication.run(Example.class, args);
        }
    }
    

    RestController 注解

    @RestController = @Controller + @ReponseBody 没啥说的了。

    EnableAutoConfiguration 注解

    如果你对@EnableAutoConfiguration不了解,那很好。因为恰巧我也不是很明白。
    这篇SpringBoot使用01_1:@EnableAutoConfiguration 和 @ComponentScan@EnableAutoConfiguration 进行了一系列的测试,验证了下面这些论述。

    通常建议将应用的main类放到其他类所在包的顶层(root package),并将 @EnableAutoConfiguration 注解到你的main类上,这样就隐式地定义了一个基础的包搜索路径(search package),以搜索某些特定的注解实体(比如@Service,@Component等) 。

    例如,如果你正在编写一个JPA应用,Spring将搜索 @EnableAutoConfiguration 注解的类所在包下的 @Entity 实体。采用root package方式,你就可以使用 @ComponentScan 注解而不需要指定 basePackage 属性,也可以使用 @SpringBootApplication 注解,只要将main类放到root package中

    @EnableAutoConfiguration 注解只会自动搜索当前类所在包下的注解实体,而@ComponentScan 会自动搜索 当前类所在包的所有子包下的注解实体。

    SpringApplication.run()

    我们的main方法通过调用 run ,将业务委托给了Spring Boot的SpringApplication类。
    SpringApplication将引导我们的应用启动Spring,相应地启动被自动配置的Tomcat web服务器。
    我们需要将 Example.class 作为参数传递给 run 方法,以此告诉SpringApplication谁是主要的Spring组件,并传递args数组以暴露所有的命令行参数


    运行代码

    直接执行main方法即可
    然后访问 `http://localhost:8080/

    image.png

    打成可执行的jar包

    • pom.xml文件中添加以下内容
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    

    spring-boot-maven-plugin 是Spring Boot包含的一个Maven插件,它可以将项目打包成一个可执行jar。

    • 然后执行 mvn clean package 打包

    • 执行jar包试试看

    D:\liuchuanwei_study\spring\spring-boot\SpringBoot-Example\springboot01\target>java -jar springboot01-0.0.1-SNAPSHOT.jar
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.1.2.RELEASE)
    
    2019-04-10 17:20:04.371  INFO 6192 --- [           main] com.example.springboot01.Example         : Starting Example v0.0.1-SNAPSHOT on DESKTOP-75IE5AL with PID 6192 (D:\liuchuanwei_study\spring\spring
    -boot\SpringBoot-Example\springboot01\target\springboot01-0.0.1-SNAPSHOT.jar started by xu in D:\liuchuanwei_study\spring\spring-boot\SpringBoot-Example\springboot01\target)
    2019-04-10 17:20:04.373  INFO 6192 --- [           main] com.example.springboot01.Example         : No active profile set, falling back to default profiles: default
    2019-04-10 17:20:05.661  INFO 6192 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2019-04-10 17:20:05.695  INFO 6192 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2019-04-10 17:20:05.696  INFO 6192 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.14]
    2019-04-10 17:20:05.712  INFO 6192 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environment
    s was not found on the java.library.path: [C:\develop\jdk\jdk1.8\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Python27\;C:\Python27\Scripts;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\Sy
    stem32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\bat;C:\develop\jdk\jdk1.8\bin;C:\develop\jdk\jdk1.8\jre\bin;C:\develop\maven\apache-maven-3.5.2\bin;D:\develop\MongoDB\Server\3.6\bin;C:\Progr
    am Files\TortoiseSVN\bin;C:\Program Files (x86)\MySQL\MySQL Server 5.7\bin;C:\WINDOWS\System32\OpenSSH\;D:\develop\nodejs\;D:\develop\Git\cmd;D:\develop\TortoiseGit\bin;D:\develop\MySQL5.5\bin;D:\devel
    op\cocos2d-x-3.17\templates;D:\develop\cocos2d-x-3.17\tools\cocos2d-console\bin;C:\Users\xu\AppData\Local\Microsoft\WindowsApps;;D:\develop\SSHSecureShell;C:\Users\xu\AppData\Roaming\npm;.]
    2019-04-10 17:20:05.825  INFO 6192 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2019-04-10 17:20:05.825  INFO 6192 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1406 ms
    2019-04-10 17:20:06.035  INFO 6192 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
    2019-04-10 17:20:06.242  INFO 6192 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2019-04-10 17:20:06.245  INFO 6192 --- [           main] com.example.springboot01.Example         : Started Example in 2.251 seconds (JVM running for 2.642)
    2019-04-10 17:20:09.845  INFO 6192 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
    2019-04-10 17:20:09.845  INFO 6192 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
    2019-04-10 17:20:09.854  INFO 6192 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms
    

    相关文章

      网友评论

          本文标题:【SpringBoot学习】01. 第一个应用

          本文链接:https://www.haomeiwen.com/subject/uqiniqtx.html