Spring Boot之Hello World

一、Spring Boot介绍

以前spring开发需要配置一大堆的xml,后台spring加入了annotaion,使得xml配置简化了很多,当然还是有些配置需要使用xml,比如申明component scan等。Spring开了一个新的model spring boot,主要思想是降低spring的入门,使得新手可以以最快的速度让程序在spring框架下跑起来。 那么如何写Hello world呢?

步骤:
(1).新建一个Maven Java 工程.
(2).在pom.xml文件中添加Spring Boot Maven依赖.
(3).编写启动类以及Controller.
(4).运行程序.

二、具体核心代码

1. pom.xml

1.1 在pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么stater poms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。

1.2 因为我们开发的是web工程,所以需要在pom.xml中引入spring-boot-starter-web,spring官方解释说spring-boot-start-web包含了spring webmvc和tomcat等web开发的特性。

1.3 如果我们要直接Main启动spring,那么以下plugin必须要添加,否则是无法启动的。如果使用maven 的spring-boot:run的话是不需要此配置的。

  <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>1.4.1.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.7</java.version>
  </properties>

  <dependencies>
        <dependency>
              <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
               <!-- 由于我们在上面指定了parent(spring boot),在这里可以不需要指定version -->
         </dependency>
  </dependencies>
  
     <build>
      <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin </artifactId>
          </plugin>
       </plugins>
    </build>
    
    <profiles>
      <profile>
        <id>jdk-1.7</id>
        <activation>
            <activeByDefault>true</activeByDefault>
            <jdk>1.7</jdk>
        </activation>
        <properties>
            <maven.compiler.source>1.7</maven.compiler.source>
            <maven.compiler.target>1.7</maven.compiler.target>
            <maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>
        </properties>
    </profile> 
  </profiles>

2. 编写启动类

2.1. 其中@SpringBootApplication申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan

/**
 * 
 * @author Jack
 *
 */
@SpringBootApplication
public class SpringBootBootstrap {
    
    public static void main(String[] args) {
        SpringApplication.run(SpringBootBootstrap.class, args);
    }
}

2.2 Controller

package com.npf.springboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 
 * @author Jack
 *
 */
@RestController
public class HelloController {
    
    @RequestMapping("/hello")
    public String hello(){
        return "hello spring boot!";
    }

}

三、运行

1. 直接运行SpringBootBootstrap的main方法

2. 访问: http://localhost:8080/hello

Github地址: https://github.com/spring-boot-learn/springboot01

参考文献:

1. spring boot起步之Hello World【从零开始学Spring Boot】

posted @ 2017-07-15 09:11  pfnie  阅读(118)  评论(0)    收藏  举报