1.2 入门案例详解

2016-02-19 21:24:00 9,912 0

1、pom.xml讲解

在上一节中的 quick start 案例中,我们在pom.xml文件中添加了如下内容:

<!-- 继承 SpringBoot的默认配置 -->
     <parent >
        <groupId> org.springframework.boot </groupId>
        <artifactId> spring-boot-starter-parent </artifactId>
        <version> 1.3.0.RELEASE </version>
     </parent >
     <!-- 添加 web 应用的依赖 -->
     <dependencies >
        <dependency>
            <groupId> org.springframework.boot </groupId >
            <artifactId> spring-boot-starter-web </artifactId>
        </dependency>
     </dependencies >

spring-boot-starter-parentspring-boot-starter-web 都称之为starter, starter的作用主要是简化 Maven项目 pom.xml文件的配置。

其中spring-boot-starter-parent是一种特殊的 starter,其是所有其他的 starter的父类,其提供了很多很多 maven的默认配置,并且包含了一个 dependency-managemen部分,意味着我们在子项目中添加 maven依赖时,可以省略 version标签。

而其他的 starter提供了事实上的依赖。例如上一节中,我们要搭建一个QuickStart的 web应用,所以我们提供一个 web starter: spring-boot-starter-web。

2、Applcation.java 详解

@RestController
@EnableAutoConfiguration
public class Application {
     @RequestMapping( "/" )
     public String hello(){
        return "Hello SpringBoot" ;
    }
     public static void main(String[] args) {
       SpringApplication. run(Application. class, args );
    }
}

在这个例子中,关于 @RestController和@RequestMapping ("/" ),不是SpringBoot 中的内容,是SpringMVC中的内容,因此不做介绍。

@EnableAutoConfiguration 注解和SpringApplication是 SpringBoot中提供的新的API:

1)其中@EnableAutoConfiguration 注解的作用是让 SpringBoot来“猜测” 如何配置 Spring。猜测的依据很简单,就是根据依赖的 jar包。因为在我们的依赖中,包含了 Tomcat和SpringMvc ,因此SpringBoot的自动配置机制就会认为这是一个 web应用。

2)在main 方法中有一个 SpringApplication类,通过调用其run方法 ,我们开始启动程序。在程序启动后, SpringBoot首先自动配置“猜测 ”到这是一个 web应用,因此会启动 tomcat,让用户通过 url来访问。