当前位置: 首页 > news >正文

SpringBoot 从application.yml中通过@Value读取不到属性值

为什么80%的码农都做不了架构师?>>>   hot3.png

package cn.exrick.xboot.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public
class PubService {

    private static final Logger log = LoggerFactory.getLogger(PubService.class);

    private MqttConfig mqttConfig;

    private static MqttClient client;

    // 在构造函数中注入mqttConfig能获取到mqttConfig从application.yml中获取到的值
    public
    PubService(@Autowired MqttConfig mqttConfig) { 
        this.mqttConfig = mqttConfig;
        init();
    }

//    @Bean
//    public
//    PubService pubService() {
//        return new PubService();
//    }

    private
    void init() {
        try {
            client = new MqttClient(mqttConfig.host, mqttConfig.clientId, new MemoryPersistence());
//            client = new MqttClient("tcp://106.14.181.253:1883", "SmartStreet", new MemoryPersistence());
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setUserName(mqttConfig.userName);
            connOpts.setPassword(mqttConfig.password.toCharArray());
            connOpts.setConnectionTimeout(10);
            connOpts.setKeepAliveInterval(20);
            client.connect(connOpts);
            client.setCallback(new PubServiceCallBack(client));
            log.trace("Pub service client Connected");
        } catch (MqttException e) {
            log.error("build Pub service failed " + e.getMessage());
        }
    }

    public
    void publishTop() {
        MqttMessage message = new MqttMessage();
        message.setQos(2);
        message.setRetained(true);
        message.setPayload("{\"CHx\":\"ON\"}".getBytes());
        try {
            client.publish("Pub/80001001/CHx", message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static
    void publishTop(String topic, MqttMessage msg) throws MqttException {
        try {
            client.publish(topic, msg);
        } catch (MqttException e) {

            log.error("public topic fail: Topic Name:\t" + topic + "fail message: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

}


package cn.exrick.xboot.mqtt;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public
class MqttConfig {

    @Value("${ssmqtt.host}")
    public String host;

    @Value("${ssmqtt.server.name}")
    public String userName;

    @Value("${ssmqtt.server.password}")
    public String password;

    @Value("${ssmqtt.clientId}")
    public String clientId;
}
package cn.exrick.xboot.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public
class PubService {

    private static final Logger log = LoggerFactory.getLogger(PubService.class);

    // 这种情况下,构造函数调用init方法就不能取到mqttConfig的值
    @Autowired 
    private MqttConfig mqttConfig;

    private static MqttClient client;


    public
    PubService() {
        this.mqttConfig = mqttConfig;
        init();
    }

//    @Bean
//    public
//    PubService pubService() {
//        return new PubService();
//    }

    private
    void init() {
        try {
            client = new MqttClient(mqttConfig.host, mqttConfig.clientId, new MemoryPersistence());
//            client = new MqttClient("tcp://106.14.181.253:1883", "SmartStreet", new MemoryPersistence());
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setUserName(mqttConfig.userName);
            connOpts.setPassword(mqttConfig.password.toCharArray());
            connOpts.setConnectionTimeout(10);
            connOpts.setKeepAliveInterval(20);
            client.connect(connOpts);
            client.setCallback(new PubServiceCallBack(client));
            log.trace("Pub service client Connected");
        } catch (MqttException e) {
            log.error("build Pub service failed " + e.getMessage());
        }
    }

    public
    void publishTop() {
        MqttMessage message = new MqttMessage();
        message.setQos(2);
        message.setRetained(true);
        message.setPayload("{\"CHx\":\"ON\"}".getBytes());
        try {
            client.publish("Pub/80001001/CHx", message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static
    void publishTop(String topic, MqttMessage msg) throws MqttException {
        try {
            client.publish(topic, msg);
        } catch (MqttException e) {

            log.error("public topic fail: Topic Name:\t" + topic + "fail message: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

}

主要问题的原因就是,构造函数的执行顺序先于类属性的赋值。在构造函数中使用属性的值且从application.yml通过@Value获取,此时Spring容器还没有向属性赋值。这是Spring Bean的声明周期的属性造成的。

 

 

转载于:https://my.oschina.net/773355/blog/3030241

相关文章:

  • python开发环境
  • 网页排版布局--从里到外先搞定结构
  • 常见的Web安全及其攻防姿势
  • 利益相关者分析
  • 长春网站建设×××,网站制作的步骤
  • spring boot @ConfigurationProperties vs @Value
  • ABAP的include关键字,Java的import, C的include和C4C ABSL 的import比较
  • websocket的那些事 - 初识
  • Easyui Tab使用
  • 通过DataWorks数据集成归档日志服务数据至MaxCompute进行离线分析
  • 分享 | 关于人工智能算法建模稳定性那些事儿
  • 金三银四,2019大厂Android高级工程师面试题整理
  • 函数的命名空间、作用域、闭包函数
  • 内核常见锁的机制与实现分析2
  • int,char指针探究
  • hexo+github搭建个人博客
  • 【腾讯Bugly干货分享】从0到1打造直播 App
  • 【许晓笛】 EOS 智能合约案例解析(3)
  • 0基础学习移动端适配
  • canvas实际项目操作,包含:线条,圆形,扇形,图片绘制,图片圆角遮罩,矩形,弧形文字...
  • Java 实战开发之spring、logback配置及chrome开发神器(六)
  • 不用申请服务号就可以开发微信支付/支付宝/QQ钱包支付!附:直接可用的代码+demo...
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 对象引论
  • 构造函数(constructor)与原型链(prototype)关系
  • 后端_MYSQL
  • 老板让我十分钟上手nx-admin
  • 入门到放弃node系列之Hello Word篇
  • 设计模式走一遍---观察者模式
  • 一起参Ember.js讨论、问答社区。
  • 赢得Docker挑战最佳实践
  • Java数据解析之JSON
  • # 透过事物看本质的能力怎么培养?
  • #1014 : Trie树
  • $ is not function   和JQUERY 命名 冲突的解说 Jquer问题 (
  • ()、[]、{}、(())、[[]]命令替换
  • (20)目标检测算法之YOLOv5计算预选框、详解anchor计算
  • (3)(3.5) 遥测无线电区域条例
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (c语言版)滑动窗口 给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度
  • (Matalb时序预测)WOA-BP鲸鱼算法优化BP神经网络的多维时序回归预测
  • (Mirage系列之二)VMware Horizon Mirage的经典用户用例及真实案例分析
  • (二)linux使用docker容器运行mysql
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (五)Python 垃圾回收机制
  • (一)基于IDEA的JAVA基础12
  • (转)jQuery 基础
  • .NET Remoting Basic(10)-创建不同宿主的客户端与服务器端
  • .netcore 获取appsettings
  • .net遍历html中全部的中文,ASP.NET中遍历页面的所有button控件
  • // an array of int
  • ?php echo ?,?php echo Hello world!;?
  • @RequestMapping处理请求异常
  • [ IOS ] iOS-控制器View的创建和生命周期
  • [ai笔记9] openAI Sora技术文档引用文献汇总