Spring Boot Hello World

一个功能:
浏览器发送 hello 请求,服务器接受请求并处理,响应 Hello World 字符串;

项目搭建

1. 创建一个 maven 工程

2. 导入 Spring Boot 相关的依赖


        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
        
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

3. 编写一个主程序,启动 Spring Boot 应用

package com.huawei.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @SpringBootApplication 来标注一个主程序类,说明这是一个 Spring Boot 应用
 */
@SpringBootApplication
public class HelloWorldMainApplication {
    public static void main(String[] args) {
        // Spring 应用启动
        SpringApplication.run(HelloWorldMainApplication.class, args);
    }
}

4. 编写相关的 Controller、Service

package com.huawei.cloud.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

5. 运行主程序测试

6. 简化部署

在pom.xml中添加插件


    
        
            
                org.springframework.boot
                spring-boot-maven-plugins
            
        
    

maven package命令打包

探究

1. 主程序

@SpringBootApplication: Spring Boot 应用标注在某个类上说明这个类是 Spring Boot 的主配置类,Spring Boot 就应该运行着类的 main 方法来启动 Spring Boot应用。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

@SpringBootConfiguration:Spring Boot 的配置类,标注在某个类上,表示这是一个Spring Boot 的配置类。(Spring Boot)

  • @Configuration:配置类上标注这个注解,配置类就相当于配置文件,也是容器中的一个组件(Spring)

@EnableAutoConfiguration:开启自动配置功能;以前我们需要配置的东西都不需要配置,Spring Boot自动配置。

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
  • @AutoConfigurationPackage:自动配置包
    • @Import(AutoConfigurationPackages.Registrar.class):Spring底层注解@Import,给容器中导入一个组件,导入的组件由AutoConfigurationPackages.Registrar.class
    • 将主配置类(@SpringBootApplication标注的类)所在包及下面所有子包里面的所有组件扫描到Spring容器中。
  • @Import(AutoConfigurationImportSelector.class):给容器中导入组件AutoConfigurationImportSelector.class,将所有需要导入的组件以全类名的形式返回,会给容器中导入非常多的自动配置类;就是给容器中导入这个场景需要的所有组件,并配置好这些组件。

你可能感兴趣的:(Spring Boot Hello World)