spring boot 简单入门 ====Hello World
个人的开发环境 eclipse + jdk 1.7 + maven
创建maven项目(没有使用过maven,百度有很多教程)
目录结构大概这样,可能一开始缺少 src/main/resources 这个源码包(这里主要是放配置文件的),不过不影响接下来的服务正常启动。
首先在配置pom.xml 文件,引入必须的jar包 spring-boot-starter-web,
加入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
配置,其他未做改动
配置pom.xml文件
整体pom.xml文件如下:
<projectxmlns="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>springboot</groupId>
<artifactId>SpringBootMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- spring boot pom文件所必须的配置 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<name>SpringBootMaven</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 引入spring-boot-starter-web jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
创建controller
package springboot.test.first.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FirstController {
@RequestMapping("/")
public String index() {
return"Hello World";
}
}
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。主要是将返回值作为字符串返回到前台,而不会解析为视图。创建启动类
关键代码,我们创建spring boot web程序的入口类:
package springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public staticvoid main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
@SpringBootApplication是spring boot最重要的一个注解,用于快捷配置启动类。启动类所在的包下的位置很重要,最好将启动类放在包的根目录下,要包含其他子包。
然后我们运行main方法,打开浏览器,因为spring boot 内嵌了一个Tomcat,所以不需要手动部署到Tomcat服务器上也可以启动web服务,在浏览器上输入http://localhost:8080/ 即可看到浏览器上的内容。
注意默认端口号为8080,如果有服务占用了端口,先停止其服务,在启动main方法。
默认端口修改
如果想修改内嵌Tomcat端口号,其中一种方法是,添加src/main/resources 源码包,默认创建项目有该源码包的忽略,在该源码包下添加application.properties 配置文件(该配置文件为spring boot 默认提供的,修改相应配置属性会覆盖spring boot 默认的配置),并添加 server.port=8088, 即可修改端口号。
再重启main方法,就可以看到端口号已经被修改。