1 eclipse新建Maven工程,选择quickstart archetype
2 POM.xml中引入相关依赖
<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.rrfare</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3 建立spring boot启动类
@ComponentScan(value = {"com.rrfare.controller"}) //
@EnableAutoConfiguration
public class App {
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
4 新建controller
package com.rrfare.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Value("${username}")
private String username;
@Value("${password}")
private String password;
@Value("${company}")
private String company;
@RequestMapping("/user")
public String getUserInfo(){
return this.username + "\n" + this.password + "\n" + this.company;
}
}
5 在src/main/resources新建application.properties,注意名称不能随意取
username=liup
password=xxxxxxx
company=gooagoo
6 执行pom.xml,clean spring-boot:run
7 Spring boot优势
(1)不用配置web.xml
(2)不用配置spring/springmvc配置文件了
(3)不用安装tomcat,spring boot内嵌Tomcat
8 相关名词解释
(1)spring-boot-starter-parent:提供spring boot工程基础maven配置
(2)spring-boot-starter-web:添加Tomcat and Spring MVC功能
(3)@EnableAutoConfiguration:根据pom.xml中引入jar自动判断工程类型并进行相应配置,例如dependency中引入spring-boot-starter-web,则判断该工程为web工程(即使在工程建立时选择quick start archetype 而不是 web archetype)
(4)@RestController:返回方法return内容,相当于@ResponseBody+@Controller
注意1:使用@RestController无法返回jsp(配置的视图解析器InternalResourceViewResolver不起作用),只有@Controller才行
注意2:如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解