使用@PropertySource动态加载不同环境的配置文件

前言

自定义配置文件是我们日常开发中经常会使用的资源,而spring只提供了类似application-* 的这中匹配方式,并不支持我们自定义的配置文件名称,例如:customize-dev.properties,但是spring提供了一个注解可以方便加载我们的自定义配置文件,它就是@PropertySource

自定义配置文件

customize-dev.properties

customize.name=dev
使用@PropertySource加载配置文件
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Data
@Component
@PropertySource(value = "classpath:customize${customize.profiles.active:}.properties")
@ConfigurationProperties(prefix = "customize", ignoreInvalidFields = true)
public class Customize {
    private String name;
}
指定配置文件
-Dcustomize.profiles.active=-dev
启动测试
import com.learning.shiro.config.Customize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CustomizeController {
    @Resource
    private Customize customize;

    @RequestMapping(value = "/")
    public ResponseEntity<?> index() {
        return new ResponseEntity<Customize>(customize, HttpStatus.OK);
    }
}
结果
{
	name: "dev"
}
扩展

以上的方式只能加载一个配置文件而且不是很优雅,可以通过实现PropertySourceFactory自定义加载配置文件,但是这种方式本人没有尝试过,有尝试过的朋友可以分享一下自己的实现方案。

import java.io.IOException;
import org.springframework.core.env.PropertySource;
import org.springframework.lang.Nullable;

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

DefaultPropertySourceFactory 是官方提供的默认的配置文件加载方式,大家可以根据业务自定义实现自己的加载方式。

总结

以上就是本片文章的全部内容,主要介绍了@PropertySoure注解的基本使用,如果有更好的方案,欢迎大家讨论分析,感谢。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值