一、讀取默認配置文件
1、application.properties:
#端口號
server.port=9090
#自定義屬性
test.msg=hello
2、用注解@Value讀取屬性
package com.gui.hello;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class HelloController {
@Value("${test.msg}")
private String msg;
@RequestMapping("/hello")
public String hello(){
return msg;
}
}
3、訪問: http://localhost:9090/test/hello
結果:
二、讀取自定義配置文件
1、步驟
1. 創建自定義配置文件
2. 將配置綁定到實體類
@Configuration //將配置文件與實體類綁定
@PropertySource(value = "classpath:/config/userinfo.properties") //指明配置文件的位置
@ConfigurationProperties(prefix = "userinfo") //指明配置文件的名稱
1
2
3
3. 在控制器中注冊實體類
@EnableConfigurationProperties(UserInfo.class) //注冊實體類
1
2、實例
1. 在resources/config目錄下創建配置文件userinfo.properties:
userinfo.name=xiaoming
userinfo.age=25
userinfo.city=HangZhou
1
2
3
2. 將配置綁定到實體類
UserInfo.java
package com.gui.hello.domain;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 用戶信息類
*/
@Configuration //將配置文件與實體類綁定
@PropertySource(value = "classpath:/config/userinfo.properties") //指明配置文件的位置
@ConfigurationProperties(prefix = "userinfo") //指明配置文件的名稱
public class UserInfo {
private String name;
private int age;
private String city;
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;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
3. 控制器中注冊實體類
UserInfoController.java
package com.gui.hello.web;
import com.gui.hello.domain.UserInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //結果返回json
@RequestMapping("/userinfo")
@EnableConfigurationProperties(UserInfo.class) //注冊實體類
public class UserInfoController {
@Value("${userinfo.name}")
private String name;
@Value("${userinfo.age}")
private int age;
@Value("${userinfo.city}")
private String city;
@RequestMapping("/hello")
public String hello(){
return "我的名字叫"+name+",我今年"+age+"歲了,我住在"+city;
}
}
4、運行結果
訪問:http://localhost:9090/userinfo/hello
結果:
————————————————
版權聲明:本文為CSDN博主「龜的小號」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/hju22/java/article/details/87871158