LLL

springboot第一个程序及相关注解解释

有 N 人看过

在b站看https://www.bilibili.com/video/BV1RE411c7RN?p=7 这个老师的视频,讲的很好很详细,下面是相关练习内容

项目约定:

image-1

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java

为了便于@ComponentScan扫描相当前入口类所在包及子包

我们的项目:

image-2

入口类:

package com.adminlll;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;


@EnableAutoConfiguration//作用:开启自动配置 根据引入依赖,如当前spring-boot-starter-web自动判断构建相关环境
@ComponentScan //作用:用来扫描相关注解 扫描范围:当前入口类所在包及子包 (解耦)
public class Application {
    //入口类
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

控制器类:

package com.adminlll.controller;

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

@RestController //=@Controller(实例化当前类为一个控制器) + @ResponseBody(讲当前方法返回值转换为json,响应给浏览器)
@RequestMapping("/hello")//加入访问空间,避免冲突
public class HelloController {

    @GetMapping("/hello")//限定GET 指定访问路径
    public String hello(){
        System.out.println("hello springboot!");
        return "hello springboot";
    }
}

application.yml:

server:
  port: 8080 #可修改端口
  servlet:
    context-path: /springboot_day1 #指定当前引用在部署到内嵌容器中的项目名

配置文件,可配置该程序相关参数。

注意注释。