誰(shuí)知道蘇州溪城水處理網(wǎng)站誰(shuí)做的今日短新聞20條
springboot提供了兩種配置信息的文件格式,application.properties和application.yml,基于直接明了,使用方便和高效的前提下下面的配置均采用yml格式配置,
注意
- yml采用縮減方式來(lái)排列
- 鍵后面緊跟冒號(hào),然后空格,最后是值
- 注意里面用到愛(ài)好數(shù)字的配置信息每個(gè)數(shù)組值前面的-(橫杠)和值之間有一個(gè)空格
properties也yml/ymal相互轉(zhuǎn)換
在線yaml轉(zhuǎn)properties-在線properties轉(zhuǎn)yaml-ToYaml.com在線yaml轉(zhuǎn)properties工具 - toyamlhttps://www.toyaml.com/
配置信息的分類(三種)
具體可以查看官網(wǎng)
Spring Boot Reference Documentationhttps://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#legal
springboot標(biāo)準(zhǔn)的配置
例如web服務(wù)的端口和上下文路徑
server:port: 9999servlet:context-path: /yuanma
其他第三方配置信息
例如集成redis
spring:data:redis:host: "localhost"port: 6379database: 0username: "user"password: "secret"
自定義配置信息(兩種獲取信息的方式)
@Value+EL表達(dá)式
例如下面配置了郵件信息
#郵件信息
mail:from: 123@qq.comto: 456@qq.comserver: smtp.qq.comport: 8888
下面用@Value+EL表達(dá)式配置
package com.burns.yuanma.admin.pojo;import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@Data
public class MailProperties {/*** 發(fā)件人*/@Value("${mail.from}")private String from;/*** 收件人*/@Value("${mail.to}")private String to;/*** 服務(wù)器地址*/@Value("${mail.server}")private String server;/*** 服務(wù)器端口號(hào)*/@Value("${mail.port}")private String port;
}
@ConfigurationProperties+prefix(前綴)
例如下面的用戶信息配置,
#用戶信息
user:address: 北京市朝陽(yáng)區(qū)安外大羊坊八號(hào)院8號(hào)樓2單元112name: 張三age: 12sex: 男hobbies:- 足球- 游泳- 騎行- 籃球- 棒球
獲取用戶信息
package com.burns.yuanma.admin.pojo;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "user")
@Data
public class UserProperties {/*** 姓名*/private String name;/*** 年齡*/private int age;/*** 性別*/private String sex;/*** 郵件*/private String email;/*** 住址*/private String address;/*** 愛(ài)好*/private String[] hobbies;
}
訪問(wèn)接口獲取信息
上面兩種方式都可以獲取信息
下面是controller
package com.burns.yuanma.admin.controller;import com.burns.yuanma.admin.pojo.MailProperties;
import com.burns.yuanma.admin.pojo.UserProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class PropertiesController {@Autowiredprivate UserProperties userProperties;@Autowiredprivate MailProperties mailProperties;@RequestMapping("/userInfo")public String userInfo(){System.out.println(userProperties.toString());return userProperties.toString();}@RequestMapping("/mailInfo")public String mailInfo(){System.out.println(mailProperties.toString());return mailProperties.toString();}}
訪問(wèn)瀏覽器
?用戶信息
http://localhost:9999/yuanma/userInfohttp://localhost:9999/yuanma/userInfo
?郵件信息
http://localhost:9999/yuanma/mailInfohttp://localhost:9999/yuanma/mailInfo
?