应用开发中,经常会使用到一些配置信息,这些配置信息通常会配置到yml配置文件中并且可能会提供给一些静态方法使用
1.yml配置参数信息
ali:
topPrefix: topPrefix
accessKey: accessKey
accessSecret: accessSecret
productKey: productKey
2.实体类接收参数值,有几个注意点
a)、该组件由spring管理,需要添加@Component
b)、该组件指定为一个配置属性类 @ConfigurationProperties(prefix = “ali”)
c)、由于属性为静态变量,spring无法直接注入值,不过通过set方法的方式可以注入依赖(PS:注set方法不能是静态方法,且不能用lombok生成,可以通过IDE手动创建)
d)、需要引入maven依赖,否则会出现截图错误
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
package com.ali.amqp.vo;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 阿里云配置
*
* @author beauhou
* @version 1.0
* @date 2020/8/11 0011 9:05
*/
@Component
@ConfigurationProperties(prefix = "ali")
public class AliConfigVo {
public static String topPrefix ;
public static String accessKey;
public static String accessSecret;
public static String productKey;
public String getTopPrefix() {
return topPrefix;
}
public void setTopPrefix(String topPrefix) {
AliConfigVo.topPrefix = topPrefix;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
AliConfigVo.accessKey = accessKey;
}
public String getAccessSecret() {
return accessSecret;
}
public void setAccessSecret(String accessSecret) {
AliConfigVo.accessSecret = accessSecret;
}
public String getProductKey() {
return productKey;
}
public void setProductKey(String productKey) {
AliConfigVo.productKey = productKey;
}
}
3.测试效果
@SpringBootApplication
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class,args);
System.out.println("topPrefix->"+AliConfigVo.topPrefix+
" accessKey->"+AliConfigVo.accessKey+
" accessSecret->"+AliConfigVo.accessSecret+
" productKey->"+AliConfigVo.productKey);
}
}