Spring Boot入门 ---- Hello World

-> 从Hello World 开始

   1、新建一个Maven项目

如何在idea新建maven项目

 

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>

3、 编写一个HelloController

 附上代码:

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方法)

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

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

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

完成......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。 
  

5:SpringApplication.run(..)的有什么作用?
         (1)启动SpringBoot应用
         (2)加载自定义的配置类,完成自动配置功能
       (3)把当前项目配置到嵌入的Tomcat服务器
       (4)启动嵌入的Tomcat服务器
     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章