SpringBoot中PropertySource注解的使用以及PropertySource注解的属性

这段时间在做项目时遇到端口号要写在配置文件中的问题,通过度娘了解了一下,在这里简要写一下自己的体会,希望对大家有所帮助
1.作用
用来加载指定的配置文件和外部文件
2.属性
PropertySource有以下几个属性
1.value为要加载的文件,可以是多个当以classpath开头时,程序会自动到classpath中读取,当以file开头时,会加载外部的文件
2.name是表示要加载文件的名称,这里要加载的配置文件必须是 唯一的不能是多个
3.encoding,设置编码,我们一般用utf-8
4.ignoreResourceNotFound,这个属性的意思是当加载的配置文件不存在时,是否报错默认false,当为true时表示文件不存在不报错,为false时表示文件不存在报错

@PropertySource(value= {"classpath:cinterface.properties","file:config/cinterface.properties"},encoding="UTF-8",ignoreResourceNotFound=true)

3.使用
@PropertySource要和@Value配合使用,@Value注解的属性为配置文件的键,对应下面的属性
配置文件

cinterface.port=10023

实体类

@Value("${cinterface.port}")
	private String port;

4.实例
配置文件

cinterface.port=10023
cinterface.LSCID=1

实体类(这里说明一下实体类好像这能定义成String类型,我定义成int会报错)

package com.modou.cinterface.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value= {"classpath:cinterface.properties","file:config/cinterface.properties"},encoding="UTF-8",ignoreResourceNotFound=true)
public class CinterfaceConfig {
	@Value("${cinterface.port}")
	private String port;
	@Value("${cinterface.LSCID}")
	private String LSCID;
	public String getPort() {
		return port;
	}
	public void setPort(String port) {
		this.port = port;
	}
	public String getLSCID() {
		return LSCID;
	}
	public void setLSCID(String lSCID) {
		LSCID = lSCID;
	}
}

如有错误或不恰当处欢迎指出

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值