学习 Spring Boot(一):第一个 Spring Boot 应用

创建一个干净的 maven 工程:

  • groupId: com.muziyuchen
  • artifactId: app
  • version: 1.0

配置

编辑 pom.xml 文件:

定义 spring boot 版本属性:

<spring.boot.version>1.3.5.RELEASE</spring.boot.version>  

添加依赖管理:

<dependencyManagement>  
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring.boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>  

添加依赖:

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

添加构建配置:

<plugin>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>  

代码

创建应用入口类 ApplicationServer.java

@SpringBootApplication
@Import(ApplicationConfiguration.class)
public class ApplicationServer {

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

}

创建应用配置类 ApplicationConfiguration.java

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class ApplicationConfiguration {  
}

创建测试 controller 类 TestController.java

@RestController
public class TestController {

    @RequestMapping("/test")
    public String test() {
        return "this is a test.";
    }

}

运行

运行 ApplicationServer,访问:http://127.0.0.1:8080/test,显示:

this is a test.