SpringBoot入门示例
创建Maven POM文件
在pom.xml添加内容如下:
<?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>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.7.RELEASE</version>
    </parent>
    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Spring boot 提供了很多有用的starter包,帮助我们构建Spring Boot应用。
spring-boot-starter-parent为我们提供下面功能:
- dependencies manager,管理Spring boot的相关依赖,这样我们在依赖其他spring boot的相关包时,可以去掉版本。
- 资源过滤
- 插件配置
- 针对application.properties/application.yml以及相关环境的application-xxx.properties/application-xxx.yml的资源过滤
spring-boot-starter-web为我们集成了tomcat插件以及Spring MVC。创建代码
创建代码结构如下:
com
 +- example
     +- myproject
         +- Application.java
         |
         +- web
             +- HomeController.java
应用主类Application.java
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
spring boot默认是打包成一个可执行的jar包,和其他java程序一样,我们需要自己写一个主类来作为程序的入口。
应用启动SpringApplication.run(),其中参数为启动类。
@Configuration:设置Application为主配置类
@EnableAutoConfiguration:这是为了能够根据jar包的依赖自动配置Spring应用,例如依赖于spring-boot-starter-web,因为spring-boot-starter-web包含了tomcat 插件以及Spring MVC,系统就会自动配置如tomcat的端口等等。
@ComponentScan:启动自动扫描组件功能
@RestController
public class HomeController {
    @GetMapping("/")
    String home() {
        return "Hello World!";
    }
}
这是一个简单的Restful Controller。
启动
IDE
如果是eclipse或Intellij这些IDE,那么直接执行Appication类的main方法即可
Maven
我们在pom里添加了插件spring-boot-maven-plugin,使用maven启动:
$ mvn spring-boot:run
可执行包
如果达成了可执行包,启动如下:
java -jar target/myproject-0.0.1-SNAPSHOT.jar
启动后,在浏览器输入http://localhost:8080访问。
 
             
             
             
             
            