这篇文章给大家分享的是有关spring boot如何实现自定义配置源的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

站在用户的角度思考问题,与客户深入沟通,找到沙坪坝网站设计与沙坪坝网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站制作、做网站、外贸营销网站建设、企业官网、英文网站、手机端网站、网站推广、域名与空间、雅安服务器托管、企业邮箱。业务覆盖沙坪坝地区。
概述
我们知道,在Spring boot中可以通过xml或者@ImportResource 来引入自己的配置文件,但是这里有个限制,必须是本地,而且格式只能是 properties(或者 yaml)。那么,如果我们有远程配置,如何把他引入进来来呢。
如何做
其实自定义配置源只需要3步
第一步,编写PropertySource
编写一个类继承EnumerablePropertySource,然后实现它的抽象方法即可,抽象方法看名字就知道作用,简单起见,这里使用一个map来保存配置,例如:
public class MyPropertySource extends EnumerablePropertySource
第二步,编写PropertySourceLocator
PropertySourceLocator 其实就是用来定位我们前面的PropertySource,需要重写的方法只有一个,就是返回一个PropertySource对象,例如,
public class MyPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource> locate(Environment environment) {
//简单起见,这里直接创建一个map,你可以在这里写从哪里获取配置信息。
Map properties = new HashMap<>();
properties.put("myName","lizo");
MyPropertySource myPropertySource = new MyPropertySource("myPropertySource",properties);
return myPropertySource;
}
} 第三步,让PropertySourceLocator生效
新建一个配置类,例如
@Configuration
public class MyConfigBootstrapConfiguration {
@Bean
public MyPropertySourceLocator myPropertySourceLocator(){
return new MyPropertySourceLocator();
}
}最后再创建/更新 META-INFO/spring.factories(如果做过自定义Spring boot开发的都知道这个文件)
org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.lizo.MyConfigBootstrapConfiguration
简单来说就是给Spring Boot说,这个是一个启动配置类(一种优先级很高的配置类)。
编写测试
测试一
@SpringBootApplication
public class Test2 {
public static void main(String[] args) throws SQLException {
ConfigurableApplicationContext run = SpringApplication.run(Test2.class, args);
Ser bean = run.getBean(Ser.class);
System.out.println(bean.getMyName());
}
@Component
public static class Ser{
@Value("${myName}")
private String myName;
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
}
}正确输出
测试二
我们在application配置文件中,引入这个变量呢,例如在application.properties中
my.name=${myName}同样,结果也是能够生效的
myName就是上面在PropertySourceLocator中写进去的配置属性。运行程序,可以看见确实是可以正确输出。
感谢各位的阅读!关于“spring boot如何实现自定义配置源”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
分享文章:springboot如何实现自定义配置源
本文网址:http://www.jxjierui.cn/article/pshdco.html


咨询
建站咨询
