清明假期闲来无事,学习了下spring boot。参考了许多网友的文章,发现大部分基于1.4之前的版本,因此踩了一些坑,在这里做下记录作为参考,防止新人继续踩坑。
1、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- spring boot 父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- spring-boot-starter相关依赖可以省去版本号,从parent继承 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、spring boot 启动类 Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication
= (默认属性)@Configuration
+ @EnableAutoConfiguration
+ @ComponentScan
,提供了自动配置和注解扫描支持。
3、Hello World 示例
@RestController
public class BaseController {
@RequestMapping("/")
public String toIndex() {
return "Hello World!";
}
}
@RestController
注解提供REST风格支持,可以将返回值直接输出到浏览器页面,若使用@Controller
则需要提供HTML页面。
以上即是spring boot之Hello World的所有代码,代码相当精简,无需任何xml配置。
4、启动应用
使用maven命令mvn spring-boot:run
或在IDE中运行Application.java
类的main()
方法,即可启动应用。启动完成后,打开浏览器,访问 http://localhost:8080 即可看到Hello World!
5、spring boot 之 Junit测试
以上Hello World示例新旧版本并无不同,而Junit在1.4版本之前和之后则略有差异
在1.4之前的版本中使用@SpringApplicationConfiguration
来指定 Spring 配置文件或者配置类的位置,在1.4版本中@SpringApplicationConfiguration
已被标记为废弃,在1.5版本中已删除,并使用@SpringBootTest
代替
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class Test {
@Test
public void test() {
……
}
}