欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot自定义properties配置

程序员文章站 2022-05-01 08:11:43
...

在实际开发web时,有时需要自己添加一些配置。

一、application.properties配置

#致诚配置
zc.rsa_key_path=E:/xxx/xxx
zc.rc4_key=abcdefghijk
zc.userid=jinxiaoxin

二、自定配置类config

package com.xxxxx.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "zc")
public class ZCConfig {
    private String rsa_key_path;
    private String rc4_key;
    private String userid;

    public String getRsa_key_path() {
        return rsa_key_path;
    }
    public void setRsa_key_path(String rsa_key_path) {
        this.rsa_key_path = rsa_key_path;
    }
    public String getRc4_key() {
        return rc4_key;
    }
    public void setRc4_key(String rc4_key) {
        this.rc4_key = rc4_key;
    }
    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid;
    }
}

三、Spring Boot入口类加上注解

//扫描config
@EnableConfigurationProperties
public class App extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder application) {
        return application.sources(App.class);
    }
}

四、如何使用

@Service
public class ZCServiceHandler {
    private static Logger LOG = Logger.getLogger(ZCServiceHandler.class);
    /**
     * 致诚配置内容
     */
    @Autowired
    //先注入
    ZCConfig zcConfig;

    public void useConfig(){
    String userId = zcConfig.getUserid();
    String rsaPubKeyFilePath = zcConfig.getRsa_key_path();// RSA 公钥绝对路径
    String rc4key = zcConfig.getRc4_key(); // RC4公钥
}
}