天天看点

SpringBoot一:入门HelloWorld

创建Maven工程

使用idea工具创建一个maven工程,该工程为普通的java工程即可

添加SpringBoot的启动器

SpringBoot要求,项目要继承SpringBoot的起步依赖spring-boot-starter-parent

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.6.RELEASE</version>
	<relativePath/>
</parent>
           
指定字符集以及JDK版本
<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>
           
SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖
<dependencies>
	<!-- Spring Boot web依赖 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>
           
SpringBoot引导类

要通过SpringBoot提供的引导类起步SpringBoot才可以进行访问

//启动方式一:启动SpringBootApplication类中的main方法
//启动方式二:使用Maven命令spring-boot:run执行即可
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
           
Controller

在引导类Application同级包或者子级包中创建Controller

@RestController
public class HelloController {

	// http://localhost:8080/hello
	@RequestMapping("/hello")
	public Map<String, String> sayHello() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("hello", "springboot");
		return map;
	}

}
           
测试

启动方式一: 启动Application类中的main方法

启动方式二: 使用Maven命令spring-boot:run执行即可

通过日志发现,Tomcat started on port(s): 8080 (http) with context path ''tomcat已经起步,端口监听8080,web应用的虚拟工程名称为空

打开浏览器访问

url

地址为:http://localhost:8080/hello

代码托管:springboot_helloworld

继续阅读