SpringBoot 有几种读取配置文件的方式

在这里插入图片描述

四种注解

先看配置文件 application.properties

user.username=CCCCXXX
user.password=123123123
user.age=18
user.salary=2000.00

1. @Value读取

@Service
public class UserServiceImpl{
	@Value("${user.username}")
	private String username;
	@Value("${user.password}")
	private String password;
	@Value("${user.age}")
	private int age;
	@Value("${user.saary}")
	private double salary;
	
	// 省略...
}

2. @PropertySource读取

@Service
@PropertySource(value="application.properties")
public class UserServiceImpl{
	@Value("${user.username}")
	private String username;
	@Value("${user.password}")
	private String password;
	@Value("${user.age}")
	private int age;
	@Value("${user.saary}")
	private double salary;
	
	// 省略...
}

配合@Value一起使用
!!!注意!!!@PropertySource读取不支持yml文件配置

3. @Environment读取

配置文件里面所有的配置都可以用Environment来获取

@Service
public class UserServiceImpl{
	
	@Autowired
	private Environment env;

	private void getUsername(){
		String username = env.getProperty("user.username");
	}
	// 省略...
}

4. @ConfigurationProperties读取

**这个注解就更屌了…**可以配合着别的注解一起使用

@Service
@ConfigurationProperties(prefix="user")
public class UserServiceImpl{
	
	private String username;
	
	private String password;
	
	private int age;
	
	private double salary;
	
	// 省略...
}

5. @ConfigurationProperties + @PropertySource注解一起使用

假如我在resources文件夹新建一个文件夹config
在创建一个配置文件two.properties内容不变,我可以这样使用

@Service
@PropertySource(value="config/two.properties")
@ConfigurationProperties(prefix="user")
public class UserServiceImpl{
	
	private String username;
	
	private String password;
	
	private int age;
	
	private double salary;
	
	// 省略...
}

综上所述四种注解均能从配置文件中读取自定义参数,也可以相互之间搭配使用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值