springboot(1.5.9.RELEASE) 入门

  • 构建项目一般在spring的官网https://projects.spring.io/spring-boot/快速开始一个项目
  • 一般在https://docs.spring.io/spring-boot/docs/获取相应版本的springboot的文档
  • github上已经有了翻译版本springboot 1.4 翻译文档,所以我们要学会站在巨人的肩膀,善用github

安装

  • springboot可以像标准库一样使用,只需引入spring-boot-*,但是通常一般使用maven构建工具
  • maven安装

一个典型的pom文件

  
    
    4.0.0

    com.example
    myproject
    0.0.1-SNAPSHOT

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.9.RELEASE
    

    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    
  

第一个springboot应用

首先需要创建一个pom.xml 文件



    4.0.0

    com.example
    myproject
    0.0.1-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.9.RELEASE
    

    


添加classpath依赖


    
        org.springframework.boot
        spring-boot-starter-web
    

编写代码

这是一个例子

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}
  • @RestController :告诉Spring使得到的字符串直接返回给调用者

  • @RequestMapping:提供路由信息

    @RestController和@RequestMapping这两个注解为spring mvc的注解(并不专门是针对Spring Boot)

  • @EnableAutoConfiguration:注解告诉Spring Boot根据你添加的jar依赖来“猜测”你将如何配置Spring,自从spring-boot-starter-web添加了Tomcat和Spring MVC之后,自动配置将假定您正在开发一个Web应用程序并相应地设置Spring

  • main方法:我们的主要方法是SpringApplication通过调用委托给Spring Boot的类run。SpringApplication将启动我们的应用程序,启动Spring,然后启动自动配置的Tomcat Web服务器。我们需要传递Example.class一个参数run来告诉SpringApplication哪个是主要的Spring组件。该args数组也被传递以暴露任何命令行参数。

运行示例

由于我们已经将 spring-boot-starter-parent加入到POM文件,我们有一个有用的run目标,我们可以用它来启动应用程序。mvn spring-boot:run从根项目目录中键入以启动应用程序

创建可执行的jar

要创建一个可执行的jar我们需要添加spring-boot-maven-plugin到我们的 pom.xml。在dependencies部分下方插入以下几行:


    
        
            org.springframework.boot
            spring-boot-maven-plugin
        
    

保存pom.xml并从命令行运行mvn package,就会在target下生成一个jar文件.这是Maven在被Spring Boot重新包装之前创建的原始jar文件.

要运行该应用程序,请使用以下java -jar命令.

你可能感兴趣的:(springboot(1.5.9.RELEASE) 入门)