javascript
Spring boot 如何读取配置文件properties中的信息
1. 用 @Value 注解
直接可以在你要用到改配置文件信息的類里面進行
具體例子如下:
@Service
public class MyCommandService {
??? @Value("${name:unknown}")
??? private String name;
??? public String getMessage() {
??????? return getMessage(name);
??? }
??? public String getMessage(String name) {
??????? return “”;
??? }
}
2 .?
@PropertySource("classpath:xxx.properties") 與 @Value 注解配合
@PropertySource?? 注解當前類,參數為對應的配置文件路徑.?
package com.yihaomen.springboot;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:application.properties")
public class GlobalProperties {
??? @Value("${name}")
??? private String name;
??? @Value("${address}")
??? private String address;???
??? public String getName() {
??????? return name;
??? }
??? public void setName(String name) {
??????? this.name = name;
??? }
??? public String getAddress() {
??????? return address;
??? }
??? public void setAddress(String address) {
??????? this.address = address;
??? }
}
3讀取自定義配置文件中的配置信息
為了不破壞核心文件的原生態,但又需要有自定義的配置信息存在,一般情況下會選擇自定義配置文件來放這些自定義信息,這里在resources目錄下創建配置文件author.properties
resources/author.properties內容如下:
author.name=Solin author.age=22創建管理配置的實體類:
package Solin.controller;import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component;//加上注釋@Component,可以直接在其他地方使用@Autowired來創建其實例對象 @Component @ConfigurationProperties(prefix = "author",locations = "classpath:author.properties") public class MyWebConfig{private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;} }注意:
在@ConfigurationProperties注釋中有兩個屬性:
locations:指定配置文件的所在位置
prefix:指定配置文件中鍵名稱的前綴(我這里配置文件中所有鍵名都是以author.開頭)
??? 使用@Component是讓該類能夠在其他地方被依賴使用,即使用@Autowired注釋來創建實例。
創建測試Controller
注意:由于在Conf類上加了注釋@Component,所以可以直接在這里使用@Autowired來創建其實例對象。
轉載于:https://www.cnblogs.com/wwqqnn123456/p/7903049.html
總結
以上是生活随笔為你收集整理的Spring boot 如何读取配置文件properties中的信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js实现元素水平垂直居中
- 下一篇: JS简单循环遍历json数组的方法