springboot入门学习1

springboot学习1

SpringBoot对Spring的缺点进行的改善和优化,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑 业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的效率。

一、springboot的核心功能

起步依赖:

起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。

自动配置:

Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定 Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。

二、快速入门

基于springboot创建一个web工程

2.1 创建java工程,导入起步依赖



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.11.RELEASE
         
    
    com.lyy
    springboot-01
    0.0.1-SNAPSHOT
    springboot-01
    Demo project for Spring Boot

    
        1.8
    

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

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-devtools
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


2.2 创建引导类

在工程的根包下创建一个引导类


@SpringBootApplication
public class Springboot01Application {

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

}

2.3 创建controller

@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/sayHello")
    public String sayHello(){
        return "hello springboot";
    }
}

运行引导类中的main方法,浏览器访问 http://localhost:8080/hello/sayHello,后台接口给前台返回了一个字符串。

三、SpringBoot工程热部署

在 pom.xml 中添加如下配置


        
            org.springframework.boot
            spring-boot-devtools
        

并在idea中设置打开自动编译功能

(1)

springboot入门学习1_第1张图片

(2)Shift+Ctrl+Alt+/,选择Registry,再把如下选项选上

springboot入门学习1_第2张图片

四、配置文件相关

SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用 application.properties或者application.yml(application.yaml)进行配置。

SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件

4.1 配置文件与配置类的属性映射方式

4.1.1 通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上

server:
  port: 80
msg: good

在bean中可以直接使用

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Value("${msg}")
    private String msg;

    @GetMapping("/sayHello")
    public String sayHello(){
        return msg;
    }
}

4.1.2 使用注解@ConfigurationProperties映射

@ConfigurationProperties注解打在一个类上,把该类放入spring容器后,可以把配置文件中指定的内容和实体类中的属性对应上,应用中就可以直接使用实体类的属性。

注意实体类中一定要有对应的get和set方法


@Component
@ConfigurationProperties(prefix = "user-config")
public class UserConfig {
    private String username;
    private int age;

   //省略get/set方法
}
user-config:
  username: tom
  age: 18

注意配置文件中的属性如果由多个单词组成时,建议使用横线隔开的这种方式。

4.2 配置的查询

可以在spring的官网上查询更多的配置

配置信息查询

示例工程:
快速入门

你可能感兴趣的:(springboot入门学习1)