SpringBoot目标是零配置。
SpringBoot提供了或者说推荐了两种配置方式:
1.properties文件
2.yml配置文件
1.yml中如何去写配置文件:
普通的写法:(字符串 数字 boolean类型 等单个值)
stuname
集合数组的写法:
stuaddress
如果是对象或者map集合:
dept
2.配置的数据如何读取到程序中
单个值读取:
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
配置整个对象和属性的关系:
package com.zhuoyue.democonfig;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
SPEL:
SP: Spring
El: EL表达式
3.三个和配置相关的注解
@PropertySource可以读取指定的配置文件
@ImportResource可以读取外部的spring配置文件
@Configuration
@Bean可以给容器中添加一个类对象
resourcces/dog.properties
dog.dname=tangyuan
dog.age=3
@PropertySource可以读取指定的配置文件
Dog.java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@ImportResource可以读取外部的spring配置文件
需要读取谁就在主启动类的上方引入这个配置即可,例如:
@Bean的作用
import com.zhuoyue.democonfig.po.Cat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
4.配置文件的占位符
user.username=zhangsan
user.jieshao=wo de ming zi jiao ${user.username}${random.int(10)}
5.多环境开发
springboot支持多种环境下的配置文件,用哪一个需要在application.properties配置文件中进行指定:
application.yml;application-dev.yml;application-test.yml;application-prod.yml
spring.profiles.active=test
6.配置文件的位置
两个位置,一个直接写在resources根目录下
或者,resources/config下都行
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!