如何让SpringBoot读取配置文件注入到配置类

2021-03-05  本文已影响0人  一块自由的砖

背景

项目中需要增加一些三方包或者sdk,需要增加独立的配置和配置项。以微信支付为例子。

实践

1.在配置文件application.properties,增加配置项
在文件中配置信息如下(微信支付的配置项)

wxpay.appID=wxdxxx
wxpay.mchID=123456
wxpay.key=sdfsfwefmd5

2.在config目录下,增加配置类
配置类如下,在设置prefix之后通过setter注入到类中

    @Configuration
    @ConfigurationProperties(prefix = "wxpay") //与配置文件中开头相同
    public class MyConfig{
        private String appID;
        private String mchID;
        private String Key;
        // 省略get set方法
    }

如果引入的配置项,是独立的配置文件或者目录,可以增加路径参数

    // 配置文件路径
    @ConfigurationProperties(prefix = "wxpay" locations="classpath:config/conf.properties") 

3.在springboot的入口类上加上
@EnableConfigurationProperties(MyConfig.class)

    @SpringBootApplication  
    @EnableConfigurationProperties({MyConfig.class,MyConfig2.class})
    public class Application {  

        public static void main(String[] args) {  
            SpringApplication.run(Application .class, args);  
        }  
    }

4.在调用的类中使用@Autowired注解,加载配置类

    @Autowired
    private MyConfig myConfig;
上一篇 下一篇

猜你喜欢

热点阅读