boot-01-helloworld

1.包结构

2.配置文件 application.properties

server.port=8888

#spring.servlet.multipart.max-file-size=10MB

3.主程序类 MainApplication

 1 package com.atguigu.boot;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.context.ConfigurableApplicationContext;
 6 
 7 /**
 8  * @Author Tianhao
 9  * @create 2021-03-10-17:59
10  */
11 
12 
13 /**
14  * 主程序类
15  * @SpringBootApplication:这是一个springboot应用
16  *
17  * @SpringBootApplication
18  *
19  * 等同于下面的三个包
20  * @SpringBootConfiguration
21  * @EnableAutoConfiguration
22  * @ComponentScan(com.atguigu.boot)  ---->默认组件扫描基础包是主程序类MainApplication所在包及其子包
23  *
24  *
25  */
26 @SpringBootApplication(scanBasePackages={"com.atguigu"})
27 public class MainApplication {
28     public static void main(String[] args) {
29         //返回IOC容器
30         ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
31         //获取容器内所有组件的名称
32         String[] names = run.getBeanDefinitionNames();
33         for (String name : names) {
34             System.out.println(name);
35         }
36     }
37 }

4. HelloController 类

package com.atguigu.boot.controller;

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

/**
 * @Author Tianhao
 * @create 2021-03-10-18:00
 */


/**
 *
 * 默认包
 * springboot会将主程序所在包及其所有子包下的组件扫描进IOC容器
 *
 * 如果组件不在主程序所在包或者其子包下,比如WorldController组件,则必须将此组件所在全包名com.atguigu,
 * 声明在主程序类的@SpringBootApplication注解后面,
 * @SpringBootApplication(scanBasePackages={"com.atguigu"}),如果多个以字符串数组的形式
 * 这样此组件才能被扫描进IOC容器
 */


//@ResponseBody 方法直接返回字符串给浏览器
//@Controller
//  @RestController  =  @ResponseBody + @Controller
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String handle01() {
        return "hello,Spring boot 2!" + " 你好";
    }
}

5. WorldController 类

 1 package com.atguigu;
 2 
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 /**
 7  * @Author Tianhao
 8  * @create 2021-03-10-22:34
 9  */
10 
11 /**
12  * 如果组件不在主程序所在包或者其子包下,比如WorldController组件,则必须将此组件所在全包名com.atguigu,
13  * 声明在主程序类的@SpringBootApplication注解后面,
14  * @SpringBootApplication(scanBasePackages={"com.atguigu"}),如果多个以字符串数组的形式
15  * 这样此组件才能被扫描进IOC容器
16  */
17 
18 @RestController
19 public class WorldController {
20     @RequestMapping("/w")
21     public String handle02() {
22         return "world";
23     }
24 }
原文地址:https://www.cnblogs.com/zui-ai-java/p/14515901.html