springBoot中读取配置文件中的自定义参数主要有两种方法:
1、使用@Value注解;
2、使用@ConfigurationProperties进将参数映射到实体类中。
配置文件截图
具体操作如下:
方法一只需要在@Value中加入自定义参数的key;
方法二需要创建 对应的实体类;
package com.springBoot.mySpringBoot.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component//将此类作为组件加载到spring
@ConfigurationProperties(prefix = "user")//prefix自定义属性的前缀
public class UserConfigProperties {
private String userName;
private Integer age;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.springBoot.mySpringBoot.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
/**
* 自定义springBoot配置文件参数
* @author wang
*
*/
@Controller
public class UserConfigInfo {
//方法一:通过@value注解来实现
//user.name user.age就是application.properties中自定义的属性
@Value("${user.userName}")
private String userName;
@Value("${user.age}")
private Integer age;
//测试方法一
@ResponseBody
@GetMapping("/demo/getUserInfo")
public JSONObject getUserInfo() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("way", "方法一");
jsonObject.put("userName", userName);
jsonObject.put("age", age);
return jsonObject;
}
//方法二:使用@ConfigurationProperties注解进行实体类映射
@Autowired
UserConfigProperties ucp;
@ResponseBody
@GetMapping("/demo/getUserInfoUcp")
public JSONObject getUserInfoByUcp() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("way", "方法二");
jsonObject.put("userName", ucp.getUserName());
jsonObject.put("age", ucp.getAge());
return jsonObject;
}
}