SpringBoot学习笔记二:配置文件中自定义参数

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;
	}
	

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值