首页新闻找找看学习计划

使用springboot 类型安全的配置封装配置信息,在SpringBoot启动时报NullPointerException错误,为啥?

0
[待解决问题]

课程路径:RocketMQ4.X教程消息队列教程
第 4 章Springboot2.X整合RocketMQ4.X实战

背景:使用了springboot 类型安全的配置封装RocketMQ配置JmsConfig,在TestController测试了封装的实体,可正常访问JmsConfig各属性值。但在PayProducer中取JmsgConfig的值确报错。

问题:启动项目时,PayProducer 中取JmsConfig的值报NullPointerException(以下代码中打印了)为什么呢?

1、PayProducer

@Component
public class PayProducer {

private DefaultMQProducer producer;

@Autowired
private JmsConfig jmsConfig;

public PayProducer() {

    System.out.println(jmsConfig);//null

    producer = new DefaultMQProducer(jmsConfig.getProducerGroup());

    producer.setNamesrvAddr(jmsConfig.getNameServer());
    start();
}

}

2、TestController

@RestController
@RequestMapping("/api/v1")
public class TestController {

@Autowired
private JmsConfig jmsConfig;

@RequestMapping("/getconfig")
public String getMQConfig() {
    String tmp="nameserver:{0},{4}topic:{1},{4}producerGroup:{2},{4}consumerGroup:{3}";
    String result= MessageFormat.format(tmp,jmsConfig.getNameServer(),jmsConfig.getTopic(),jmsConfig.getProducerGroup(),jmsConfig.getConsumerGroup(),"\r\n");
    return result;
}

}

3、JmsConfig

@Component
@PropertySource("classpath:config.properties")
@ConfigurationProperties(prefix = "rocketmq")
public class JmsConfig {

private String nameServer;

private String topic;

private String consumerGroup;

private String producerGroup;

public String getNameServer() {
    return nameServer;
}

public void setNameServer(String nameServer) {
    this.nameServer = nameServer;
}

public String getTopic() {
    return topic;
}

public void setTopic(String topic) {
    this.topic = topic;
}

public String getConsumerGroup() {
    return consumerGroup;
}

public void setConsumerGroup(String consumerGroup) {
    this.consumerGroup = consumerGroup;
}

public String getProducerGroup() {
    return producerGroup;
}

public void setProducerGroup(String producerGroup) {
    this.producerGroup = producerGroup;
}

}

4、config.properties

rocketmq.nameserver=33.107.79.33:9876
rocketmq.topic=xdclass_pay_test_topic_666
rocketmq.consumerGroup=pay_consumer_group
rocketmq.producerGroup=pay_producer_group

cxiaoluab的主页 cxiaoluab | 初学一级 | 园豆:26
提问于:2019-08-13 17:12
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册