[SpringBoot 2.x ] 开发实战day3,SpringBoot自定义配置(包括List、Map)

开发过程中,引入自定义配置是很常见的,主要记录两种:
1、@Value() 注解
2、@ConfigurationPropertie()注解

一、配置文件引入问题

springboot支持两种配置文件:*.properties 和 *.yml
首先先提一下,在springboot 1.5版本以后是通过@PropertySource(“path”)无法加载YAML文件,官方也给出说明

24.7.4 YAML Shortcomings
YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.

如果想引入yml文件,有两种方式:
① 将自定义配置放在application-*.yml中,
② 通过PropertySourcePlaceholderConfigurer来加载yml文件

上代码

// 加载YML格式自定义配置文件
	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
   
		PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
		YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
		yaml.setResources(new FileSystemResource("config.yml"));//File引入
//		yaml.setResources(new ClassPathResource("youryml.yml"));//class引入
		configurer.setProperties(yaml.getObject());
		return configurer;
	}

二、自定义配置

本篇以*.properties为例

1、@Value() 注解

   引入配置文件

/**
 * 程序入口
 * @author guocheng.L
 */
@SpringBootApplication
// 加载配置文件
@PropertySource("classpath:config2.properties") 
public class MyspringbootApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(MyspringbootApplication.class, args);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值