使用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;
}