spring-boot 学习笔记三:spring-boot-helloworld

spring-boot 学习笔记三:spring-boot-helloworld

  • spring-boot入门helloworld

spring-boot入门helloworld

​ 使用spring-boot创建第一个项目helloworld,这里我使用eclipse为例,IDEA目录结构是一样的,创建项目的方式和第二篇文章一样,不会的可以去 spring-boot 学习笔记二:创建spring-boot项目的几种方式里面详细介绍了创建spring-boot项目的及中方式。废话不多说了。开始!!!!!!!!!

首先我们在com.zeriter包中新建一个名为hello的包,这个包用于存放HelloController类。

spring-boot 学习笔记三:spring-boot-helloworld_第1张图片

package com.zeriter.hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * spring boot 入门01 helloworld
 * @author zeriter zhang
 * @date 2019年5月11日
 */
@RestController
public class HelloController {
	
	/**
	 * helloWorld入门示例
	 * @author zeriter zhang
	 * @date 2019年5月11日
	 */
	@RequestMapping("/hello")
	public String helloWorld() {
		return "hello world";
	}
}

ps:其中我们是用@RestController注解标注HelloController声明这是一个Controller类。@RestController这相当于@Controller+@ResponseBody。如果你不习惯这么写也可以写成下面这样:

package com.zeriter.hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * spring boot 入门01 helloworld
 * @author zeriter zhang
 * @date 2019年5月11日
 */
@Controller
public class HelloController {
	
	/**
	 * helloWorld入门示例
	 * @author zeriter zhang
	 * @date 2019年5月11日
	 */
	@RequestMapping("/hello")
    @ResponseBody
	public String helloWorld() {
		return "hello world";
	}
}

​ 这个时候我们的第一个入门程序hello world就完成了,启动spring-boot项目,我们只需要启动捕获2即可,这是因为spring-boot内置了tomcat容器,不需要我们自己下载tomcat容器。直接RunAs-》Java Application就可以启动我们的项目。当出现:

spring-boot 学习笔记三:spring-boot-helloworld_第2张图片

表示我们的项目已经启动完成,同时我们可以看到我们使用的是8080端口,接下来就是测试了:

spring-boot 学习笔记三:spring-boot-helloworld_第3张图片

​ 值得注意的是spring-boot默认访问是不需要加项目名称的,如上图所示我们发送localhost:8080/hello请求时没有加上项目名,也成功返回了我们的hello world字符串,当然我们也可以修改这些spring-boot的默认配置。

​ 在我们项目中有这个配置文件:

QQ截图20190516141230

​ 这个文件是不是很熟悉!!,没有的小伙伴可能是application.yml文件两者的作用是相同的,都没有的情况下可以自己新建一个,但是文件名必须是application,如果不叫这个名需要我们修改很多东西,得不偿失!其中我们可以在这个文件修改spring-boot的一些默认设置。例如:我们不想使用tomcat的8080端口,而使用80端口可以配置如下

application.properties文件:

#修改tomcat的端口
server.port=80
#加上项目名访问
server.servlet.context-path=/hello

application.yml

#作用与application.properties相同。
server:
  port: 80
  servlet:
    context-path: /hello

git项目地址:spring-boot-hello

你可能感兴趣的:(学习笔记)