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

发布于 2022-09-12 03:39:06 字数 1617 浏览 10 评论 0

描述

在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();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放赐 2022-09-19 03:39:06
@PropertySource默认只支持读取properties文件 yaml文件需要自定义PropertySourceFactory 如果是spring boot 项目写在applciation.yml文件中不需要加@PropertySource,如果是spring cloud 项目写在bootstrap.yml文件中不需要加@PropertySource
呆° 2022-09-19 03:39:06

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文