最近spring boot较火,抽空学习了一下,但是看教程需要通过继承的方式搭建,折腾了半天搭了一个不用继承parent的版本
-
环境准备工作:采用eclipse+maven来构建
-
jdk:1.7
- maven:3.3.9
1 新建一个maven项目
1.1新建一个maven项目:
1.2 选择一个web项目
1.3 设置名称
1.4 创建好项目后目录结构如下:
2 引入spring boot
2.1编辑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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dtf</groupId>
<artifactId>spring-boot-test-1</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-test-1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<!--ImportdependencymanagementfromSpringBoot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.4.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-test-1</finalName>
</build>
</project>
保存文件后maven=>update project
注意:由于开始我是新建的一个web类型的项目所以,这里war要改为jar
2.2 新建一个Application.java文件到com.dtf目录下
文件名随意,但是这个文件必须放在所有Controller的上一级包下,否则报404,这里扫描Controller的注解是根据main方法中的SpringApplication.run(Application.class, args); Application这个类的路径来扫描注解
package com.dtf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
到此可以启动一下,试试能不能启动,如果出现如下提示,恭喜你,引入jar包什么的,没有问题了~
2.3创建第一个Controller
package com.dtf.web;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping(value="/index")
@RestController
public class IndexController {
@RequestMapping
public String hi() {
return "hi";
}
@RequestMapping(value="/hi")
public String sayHi(@RequestParam String name){
return "hi,"+name;
}
@RequestMapping(value="/getMap/{name}")
public Map getMap(@PathVariable String name){
Map map = new HashMap();
map.put("name", name);
return map;
}
}
3.测试
3.1直接访问
3.2带参数访问
3.3通过路径方式带参访问
Spring boot 第一个项目就这么简单的就启动了,并且在过程中并没有配置哪怕一个mvc的xml
具体见附件