时隔多年又开始写博客了 最近做项目时发现 一个问题

 @Resource
 private RocketMQTemplate rocketMQTemplate;

不知道如何自动注入进来了项目里也没用@Bean之类 经过探究源码如下首先引入的包是

  <dependency>
            <groupId>org.apache.rocketmq</groupId>
            <artifactId>rocketmq-spring-boot-starter</artifactId>
            <version>2.0.3</version>
  </dependency>
 类 RocketMQAutoConfiguration

 @Bean(
        destroyMethod = "destroy"
    )
    @ConditionalOnBean({DefaultMQProducer.class})
    @ConditionalOnMissingBean(
        name = {"rocketMQTemplate"}
    )
    public RocketMQTemplate rocketMQTemplate(DefaultMQProducer mqProducer, ObjectMapper rocketMQMessageObjectMapper) {
        RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
        rocketMQTemplate.setProducer(mqProducer);
        rocketMQTemplate.setObjectMapper(rocketMQMessageObjectMapper);
        return rocketMQTemplate;
    }

你看这个类有自动注入用@Bean了 但之前你必须得有

 

application.properties

rocketmq.producer.group=producer1

一个基本配置  为什么  因为上面代码 

@ConditionalOnBean({DefaultMQProducer.class})他的意思是在注入这个bean之前 必须有DefaultMQProducer这个bean 之后我们在看看
RocketMQAutoConfiguration.class  
@Bean
    @ConditionalOnMissingBean({DefaultMQProducer.class})
    @ConditionalOnProperty(
        prefix = "rocketmq",
        value = {"name-server", "producer.group"}
    )
    public DefaultMQProducer defaultMQProducer(RocketMQProperties rocketMQProperties) {
        Producer producerConfig = rocketMQProperties.getProducer();
        String nameServer = rocketMQProperties.getNameServer();
        String groupName = producerConfig.getGroup();
        Assert.hasText(nameServer, "[rocketmq.name-server] must not be null");
      ..............

显而易见 要想实例化这个bean 必须

@ConditionalOnProperty(
    prefix = "rocketmq",
    value = {"name-server", "producer.group"}
)得有这个属性

另外 关于这么自动注入这个属性

@Component
@ConfigurationProperties(
        prefix = "ceshi"
)
public class Test {
    private String nameServer;
    private String bb;
    private String bbName;

就是这样 有个小问题 经过试验

不管是
rocketmq.nameServer=127.0.0.1:9876
还是
rocketmq.name-server=127.0.0.1:9876
还是
rocketmq.nameserver=127.0.0.1:9876
实体类里 nameServer都可以正常注入

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐