Spring Boot入门 —- Hello World

导读:本篇文章讲解 Spring Boot入门 —- Hello World,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

-> 从Hello World 开始

   1、新建一个Maven项目

如何在idea新建maven项目

Spring Boot入门 ---- Hello World

 

2、在pom.xml导入依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <dependencies>
        <!--Spring boot的核心包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--Spring boot整合web开发的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

Spring Boot入门 ---- Hello World

3、 编写一个HelloController

Spring Boot入门 ---- Hello World

 附上代码:

package cn.ok;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@Controller
public class HelloController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello! Boot!!";
    }

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

4、启动(main方法)

Spring Boot入门 ---- Hello World

这样,一个SpringBoot的项目就启动起来了;

这时,可以在控制台上看到 8080 的端口信息(因为springboot内置了tomcat)。

5、访问 http://localhost:8080/hello 

Spring Boot入门 ---- Hello World

完成……SpringBoot就是这么方便快捷!!!


 -> 对上面Demo的一些小结:

1:对于SpringBoot项目应该打什么包?
   
 无论是普通应用还是web
应用,都打jar包就可以了。
 
2:而为什么要在pom.xml中使用父项目spring-boot-starter-parent呢? 
     
因为它帮我们管理和导入了许多的基础依赖。
 
3:为什么项目直接启动起来就能在浏览器访问?
      因为引入了 
spring-boot-starter-web ,它集成了运行网站应用的相关环境和工具(SpringMVC / Tomcat / Jackson 等等);
      依赖中
嵌入的
Tomcat9
服务器
,
默认端口
8080
 
4: 为什么要@SpringBootApplication注解?
   
     它内部是3大注解功能的集成:
       (1)@ComponentScan: 开启组件扫描   ;
       (2)@SpringBootConfifiguration: 作用等同于@Confifiguration
注解,也是用于标记配置类;
       (3)@EnableAutoConfifiguration: 内部导入AutoConfifigurationImportSelector。 
  

Spring Boot入门 ---- Hello World

5:SpringApplication.run(..)的有什么作用?
         
(1)启动SpringBoot应用
         (2)加载自定义的配置类,完成自动配置功能
       (3)把当前项目配置到嵌入的Tomcat服务器
       (4)启动嵌入的Tomcat服务器

     

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/117877.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!