Spring Boot框架搭建
程序员文章站
2022-07-12 13:39:18
...
目录
一、Spring Boot概述
Spring Boot 是 Spring 框架的一个新的子项目,用于创建 Spring 4.0 项目。它可以自动配置 Spring 的各种组件,并不依赖代码生成和 XML 配置文件。Spring Boot 也提供了对于常见场景的推荐组件配置。Spring Boot 可以大大提升使用 Spring 框架时的开发效率。
二、Spring Boot的优点
- 轻松创建独立的Spring应用程序。
- 内嵌Tomcat、jetty等web容器,不需要部署WAR文件。
- 提供一系列的“starter” 来简化的Maven配置,不需要添加很多依赖。
- 开箱即用,尽可能自动配置Spring。
三、Spring Boot框架搭建
第一步:创建一个maven jar项目。
|
|
|
|
第二步:在pom.xml添加spring-boot-starter-web依赖。
<?xml version="1.0" encoding="UTF-8"?>
<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.hedong</groupId>
<artifactId>SpringBootDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>SpringBootDemo</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--spring boot 父依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<!--spring boot 配置web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
第三步:在pom.xml文件上右键选择maven→reimport导入依赖,完成后左边External Libraries下将会自动导入很多关于Spring的依赖。
|
|
第四步:写一个控制器如下,然后写一个main方法把程序跑起来
HelloController.java
package com.hedong.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController//相当于声明Controller - 提共restful 风格
@EnableAutoConfiguration//自动配置,不需要写spring的配置文件
public class HelloController {
@RequestMapping("/hello")//映射路径
@ResponseBody//响应体
public String hello() {
return "Hello World";
}
public static void main(String[] args) {
//启动程序
SpringApplication.run(HelloController.class, args);
}
}
第五步:点击图中绿色三角形启动程序,在浏览器中访问http://localhost:8080/hello
上一篇: Spring入门及初识IOC