SpringBoot入门-HelloWorld详解

什么是SpringBoot

简而言之,它就是一个简化新Spring应用的初始搭建以及开发过程的框架。

第一个项目-HelloWorld

大多数人第一个项目都是HelloWorld,springboot也不例外,从helloworld最基础开始了解开始。

1、创建项目

本次项目使用的是idea
点击spring Initializr,在project SDK,选好自己的java版本,正常都配好了,直接下一步即可。
如果进不去,可以选择Custom:输入http://start.spring.io/,如果还是不行,就换成手机热点。
SpringBoot入门-HelloWorld详解_第1张图片
Group是项目组织唯一的标识符,对应JAVA的包的结构
Artifact是项目的唯一的标识符,对应的是项目的名称(不能大写
其它不需要修改,直接下一步
SpringBoot入门-HelloWorld详解_第2张图片
勾选个Web里的Spring Web,然后继续下一步即可。
SpringBoot入门-HelloWorld详解_第3张图片
这里就是修改你项目的位置,可直接下一步。
SpringBoot入门-HelloWorld详解_第4张图片

或者也可以进入https://start.spring.io/,进行新建一个项目并下载。

2、pom.xml

pom.xml是maven的项目描述文件,即导入依赖的地方

spring-boot-starter-web:spring-boot场景启动器;帮我们导入了web模块正常运行所依赖的组件;

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

3、启动类

它已经帮我们写好了启动类
@SpringBootApplication是用来标注为启动类。ctrl+鼠标左键点进去看源码(粗略说说)
它里面主要有三个注解
@ComponentScan:定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中
@EnableAutoConfiguration:开启自动配置功能。
@SpringBootConfiguration:这个注解就是@configuration的派生注解,跟他的功能是一样的,用来标注这个类为配置类。

@SpringBootApplication
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }
}

4、controller

创建一个controller类

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }
}

方法return里的就是返回值了
@Restcontroller=@Controller+@ResponseBody
直接将上面代码@Restcontroller改成@Controller会报错
SpringBoot入门-HelloWorld详解_第5张图片
简单来说就是@Restcontroller是用来返回json数据到页面的
而@Controller是用来返回到指定页面,如果加了@RespnseBody就和@Restcontroller功能一样。
@RequestMapping是用来注解映射请求路径的。
如@requestMapping("/hello"),就是在网页上输入localhost:8080 /hello。这里的/hello就是@requestMapping注解括号里的值。
前面端口号默认为8080.可以在application.properties中修改(添加server.port=8081)运行一下能发现控制台已经变了,地址那也该改成对应的。
在这里插入图片描述

5、运行

运行一下启动类,便能看到控制台的输出
再在浏览器上输入localhost:8081/hello(前面改了端口为8081)
SpringBoot入门-HelloWorld详解_第6张图片
这样简单的hello world就完成了。

你可能感兴趣的:(springboot)