SpringBoot读取配置文件自定义值

使用Spring上下文中的环境获取

bootstrap.yml文件中添加配置

jidi.name: 基地
jidi.age: 24

​ java代码注入 Environment,通过上下文环境获取定义的配置:

@Autowired
private Environment environment;


/**
 * 通过上下文环境获取定义的配置
*/
String name = environment.getProperty("jidi.name");
String age = environment.getProperty("jidi.age");

使用@Value注解获取

// 使用SPEL表达式获取值,如果值不存在,就会使用:后面的默认值

@Value("${jidi.name:基地的名字}")
private String name;

@Value("${jidi.age:30}")
private Integer age;

通过@ConfigurationProperties注解获取

​ 通过 @ConfigurationProperties 注解获取,需要指定前缀 prefix,会自动映射成对象。@PropertySource 可以指定属性定义的配置文件,如果不使用默认读取 application.yml

​ 使用 @ConfigurationProperties注解的前提必须使用 @Component 注解注释成一个Bean 或者使用 @EnableConfigurationProperties 注解明确要作为属性配置的类名称。

方式一,使用 @Component 声明为 bean

/**
* 方式一,使用@Component 声明为 bean
*/
@Data
@Component
@ConfigurationProperties(prefix = "jidi")
@PropertySource(value = {"classpath:bootstrap.yml"})
public class Jidi {
   
    private String name;

    private Integer age;
}

​ 方式二,使用 @EnableConfigurationProperties 明确使用哪个类

/**
 * 方式二,使用@EnableConfigurationProperties 明确使用哪个类
 */

@EnableScheduling
@EnableConfigurationProperties(value = Jidi.class)
@EnableFeignClients(basePackages={"com.aupup.user.api"})
public class ItemAutoConfiguration {

}


@Data
@ConfigurationProperties(prefix = "jidi")
@PropertySource(value = {"classpath:bootstrap.yml"})
public class Jidi {
   
    private String name;

    private Integer age;
}

​读取配置文件为一个数组,使用方式一样,只是接收参数要与文件中定义的结构保持一致,下面是个例子:

inbox.template:
  list:
    - key: inbox.order.create.supplier.receive
      title: 订单待接单
      type: 2
      content: "【订单待接单】尊敬的${receiverUserName},采购商“${developerName}”向您下了一个订单“${orderName}”,#请点击及时接单#。"
    - key: inbox.order.closed.supplier.receive
      title: 订单已关闭
      type: 2
      content: "【订单已关闭】尊敬的${receiverUserName},订单“${orderName}”已被采购商${developerName}关闭,请知悉。"
    - key: inbox.order.completed.supplier.receive
      title: 订单已完成
      type: 2
      content: "【订单已完成】尊敬的${receiverUserName},订单“${orderName}”已完成,请知悉。"
/**
 * 站内信配置信息读取配置类
 */
@PropertySource(value = "classpath:templates/inbox/inbox-template.yml")
@Component
@Data
@ConfigurationProperties(prefix = "inbox.template")
public class InboxTemplate implements Serializable {

    /**
    * 属性名必须与配置文件中的一致,此处必须为list
    */
    private List<InboxTemplateInfo> list = new ArrayList();

}


/**
 * 站内信配置封装实体
 */
@Data
public class InboxTemplateInfo implements Serializable {

    private String key;

    private String title; 

    private Integer type;

    private String content;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值