rabbitmq: host: 127.0.0.1 password: root port: 5672 username: root public class RabbitmqProperties { @Value("${rabbitmq.host}") private String rabbitmqHost; @Value("${rabbitmq.port}") private String rabbitmqPort; @Value("${rabbitmq.username}") private String rabbitmqUsername; @Value("${rabbitmq.password}") private String rabbitmqPassword; }
package java456.com.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * 陈豪 创建 * wx:xiaomao0055 * qq:14496453 * 读取配置文件的属性。 */ @Configuration @ConfigurationProperties(prefix = "mqtt") public class MqttProperties { private String url; private String clientId; private String topics; private String username; private String userpwd; private String timeout; private Integer keepaLive; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getTopics() { return topics; } public void setTopics(String topics) { this.topics = topics; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public Integer getKeepaLive() { return keepaLive; } public void setKeepaLive(Integer keepaLive) { this.keepaLive = keepaLive; } } 使用的话注入使用如下: @Autowired MqttProperties mqttProperties ; @Configuration public class MqttConfig { @Autowired MqttProperties mqttProperties ; @Autowired SensorService sensorService ; @Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); MqttConnectOptions options = new MqttConnectOptions(); String url[] = mqttProperties.getUrl().split(","); options.setServerURIs(url); //这个url 可以 字符串数组。 options.setUserName(mqttProperties.getUsername()); options.setPassword(mqttProperties.getUserpwd().toCharArray()); options.setKeepAliveInterval( mqttProperties.getKeepaLive()); options.setCleanSession(false);//接受离线消息 factory.setConnectionOptions(options); return factory; } main方法调用。 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class UtilApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(UtilApplication.class, args); MqttProperties mqttProperties = context.getBean(MqttProperties.class); String url = mqttProperties.getUrl(); String clientId = mqttProperties.getClientId(); // 其他属性... // 在这里使用属性值进行操作 } }
站长微信:xiaomao0055
站长QQ:14496453