yml配置文件与属性如何利用弹簧引导实现加载

  介绍

本篇文章给大家分享的是有关yml配置文件与属性如何利用弹簧引导实现加载,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

包com.example.config;
  
  进口org.springframework.beans.factory.annotation.Autowired;
  进口org.springframework.context.annotation.Configuration;
  进口org.springframework.context.annotation.PropertySource;
  进口org.springframework.core.env.Environment;/* *
  * @author: GrandKai
  * @create: 2016-09-01福音11:24
  */@ configuration
  @PropertySource (ignoreResourceNotFound=true值=https://www.yisu.com/zixun/{“类路径:/config/email.properties”、“类路径:/config/email.yml”}, name="电子邮件")
  公共类配置{}

需要在ApplicationContext中注册配置

=(AnnotationConfigEmbeddedWebApplicationContext) app.run AnnotationConfigEmbeddedWebApplicationContext上下文(“参数1“);
  context.register (Config.class); 

用以下方式取值

环境env=context.getEnvironment ();
  System.out.println (env.getProperty (“address")); 

电子邮件。yml文件配置如下:

服务器:   地址:127.0.0.1

公共类主要{
  公共静态void main(字符串…args) {//初始化命令行解析
  OptionParser解析器=new OptionParser ();
  parser.accepts (“greeting") .withRequiredArg ();
  OptionSet选项=parser.parse (args);//创建实际的春天PropertySource
  PropertySource<及# 63;比;ps=new JOptCommandLinePropertySource(选项);//设置Spring上下文
  所ctx=new所();
  .getPropertySources ctx.getEnvironment () () .addLast (ps);//注册房地产源与环境
  
  ctx.register (Greeter.class);
  ctx.refresh ();
  迎宾迎宾=ctx.getBean (Greeter.class);
  greeter.sayGreeting ();
  }
  }
  
  @ component
  类迎宾{
  @ inject私人环境env;//下面的也行//@ value(“${问候}“)//私人字符串的问候;/* *
  *打印& # 39;问候# 39;财产如果它存在,否则,“欢迎光临!“。
  */公共空间sayGreeting () {
  System.out.println (env.getProperty (“greeting",“欢迎光临!“));
  }
  }
  
  
  
  
  公共静态void main (String [] args) {
  SimpleCommandLinePropertySource ps=new SimpleCommandLinePropertySource (args);
  @SuppressWarnings (“resource")
  所ctx=new所();
  .getPropertySources ctx.getEnvironment () () .addFirst (ps);
  ctx.register (ApplicationConfig.class);
  ctx.refresh ();
  }
  
  
  @ configuration
  @EnableScheduling
  @ComponentScan (“com.mycompany.package")
  @PropertySource (
  值=https://www.yisu.com/zixun/{“类路径:/application.properties”、“文件:$ {config.location}},
  ignoreResourceNotFound=true
  )
  类ApplicationConfig {
  
  @ bean
  公共静态PropertySourcesPlaceholderConfigurer propertyConfigurer () {
  返回新PropertySourcesPlaceholderConfigurer ();
  }
  }
  
  @ component
  MyComponent类添加{
  
  @ value (" $ {my.property.data} ")
  私人字符串myPropertyData;
  
  
  @Scheduled (fixedDelayString=" $ {schedule.delay.period} ")
  公共空间run () {
  :
  }
  }

以上就是yml配置文件与属性如何利用弹簧引导实现加载,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。

yml配置文件与属性如何利用弹簧引导实现加载