springboot#@ConfigurationProperties注解获取配置属性值为NULL?

描述

在util模块中创建了用于jwt的配置,通过@ConfigurationProperties注解获取,并在另一个模块(auth)中注入时初始化,但得到的值全部为NULL

  • 尝试将配置文件写在auth中: 报配置文件不存在
  • 尝试写在application.yml中: NULL

求指点,拜托了!

我的配置文件

jwt:
  secret: sc@Login(Auth}*^31)&czxy% # 登录校验的明文
  pubKeyPath: D://rsa//rsa.pub # 公钥地址
  priKeyPath: D://rsa//rsa.pri # 私 钥地址
  expire: 30 # 过期时间,单位分钟

我的JavaBean

@Slf4j
@Data
@PropertySource("classpath:config/auth.yml")
@ConfigurationProperties(prefix = "jwt")
@Configuration
public class JWTProperties {

    private String secret; // 密文

    private String pubKeyPath;// 公钥

    private String priKeyPath;// 私钥

    private int expire;// token过期时间

    private PublicKey publicKey; // 公钥

    private PrivateKey privateKey; // 私钥

    //被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次
    @PostConstruct
    public void init() {
        try {
            log.info("密文: " + secret);
            log.info("公钥地址: " + pubKeyPath);
            log.info("私钥地址: " + priKeyPath);
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);

            if (!pubKey.exists() || !priKey.exists()) {
                // 生成公钥和私钥并写入文件
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败! " + e);
            throw new RuntimeException();
        }
    }
}
阅读 8.1k
2 个回答
@PropertySource默认只支持读取properties文件 yaml文件需要自定义PropertySourceFactory 如果是spring boot 项目写在applciation.yml文件中不需要加@PropertySource,如果是spring cloud 项目写在bootstrap.yml文件中不需要加@PropertySource

先看路径resource/config/auth.yml这是否正确。
然后需要创建属性的set方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题