spring boot(学习笔记第一课)
- spring boot入门
>>>学习视频
学习内容:
- IDE (IntelliJ IDEA)
- spring boot起步 https://start.spring.io/
- git代码管理
- hello,world
- 增加hello controller
1. IDE(IntellJ IDEA)
IntellJ IDEA是目前最流行的Java开发IDE,在开发中较为常用。我们采用免费的Community(社区版)
IDEA Community版
2. spring boot起步
spring boot starter
我们指定:Project=Maven,Language=Java.基本上保持默认。
3. git代码管理
代码管理我们采用gitee.com来进行。
GIT代码托管库
- 注册账号。
- 生成公钥密钥对。
ssh-keygen -t rsa
id_rsa
私钥文件(不能给其他人,只是本地的使用)
id-rsa.pub
登录给gitee.com
- 之后将公钥文件登录到gitee.com自己的账号中。
右上角->下拉菜单->账号设定->安全设定->SSH公钥
- 创建一个spring boot代码库进行代码管理。
- 利用git bash进行代码的下载。
git clone git@gitee.com:finlay-xiao/spring-boot-hello.git
这里的用户名改成自己的
4. hello,world
- 将步骤2下载的解压缩,之后放到上面的git工程里面。
- 将最初版的spring boot hello程序push到git仓库。
- 使用IntelliJ IDEA将spring-boot-hello文件夹打开。
- 增加我们的第一个hello,world controller
注意我们一定要将各种组件component,configuration和controller的类放在DemoApplication的子包下面。
例如,我们的例子中:
主类所在包是:com.example.demo.DemoApplication;
Controller类的所在包是:com.example.demo.Controller;
如果不是子包结构的话,DemoApplication类的@SpringBootApplication
注解不会就行扫描,也就是不会将controller纳入到我们的SpringBoot工程中。
如果我们是在不希望用这种默认的子包的方式,那么可以指定scan报名的方式。这样的话就没有任何限制了。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.example.package1", "com.example.package2"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
之后我们开始Controller的编码。
- 增加hello controller
- 对于pom.xml文件增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
增加完了类的依赖之后,要对IntelliJ IDEA进行maven的刷新。
2. 编写我们的controller类
这里必须用RestController!
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello,world";
}
}
如果在有的类IntelliJ IDEA找不到,那么可以用快捷键Alt-Enter
进行快速的import。
3. 找到main class,执行启动。
4.这样就出现这样的log,正常启动了。
Tomcat initialized with port 8080 (http)
Tomcat started on port 8080 (http) with context path '/'
这里默认是http协议,并且是8080端口。
5.打开浏览器,进行访问。
这里必须用http访问,目前的浏览器默认都是https,所以注意输入
浏览器中的第一个hello,world就出来了。