SpringBoot

快速入门

1.导入依赖

    <!-- SpringBootParent标签 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
    </parent>

    <!-- SpringBoot起步依赖 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
     <!-- 解决自定义对象封装数据警告 -->
        <dependency>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-configuration-processor</artifactId>
    		<optional>true</optional>
		</dependency>
    </dependencies>

2.编写引导类

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

3.编写核心配置文件

  • application.properties
  • application.yml 【最常用】
  • application.yaml

SpringBoot配置文件加载顺序

propertiex > yml > yaml

4.常用配置 - yml

  • 端口号

    server:
      port: 80
    
  • 自定义数据

    一级属性名:
    	二级属性名: 数据
    

    使用@Value读取单个数据,属性名引用方式:$

  • Environment对象

    enterprise:
    	arg1:arg1
    	arg2:arg2
    	arg3:arg3
    
    @Autowired
    private Environment env
    
    public void getByEnterprise(){
        env.getProperty("enterprise.arg1");
        env.getProperty("enterprise.arg2");
        env.getProperty("enterprise.arg3");
    }
    
  • 配置文件内容绑定实体对象

    定义实体,类上标记注解,在需要获取数据的类上直接注入bean即可获取

    public class Enterprise {
        private String name;
        private Integer age;
        private String tel;
        private String[] subject;
        //自行添加getter、setter、toString()等方法
    }
    
    enterprise:
    	arg1:arg1
    	arg2:arg2
    	arg3:arg3
    
    @Component
    @configurationProperties(prefix = "enterprise")
    public class Enterprise {
    	private string arg1;
    	private string arg2;
    	private string arg3;
    }
    
    
posted @ 2023-05-15 01:32  xuruiRyan  阅读(15)  评论(0编辑  收藏  举报