springboot静态代码块中读取配置文件yml

1、配置文件application.yml

mqtt:
  client:
    username: admin
    password: public

2、

@Configuration
public class MqttConfig {
​
    private static String username;
​
    private static String password;
    
    @Value("${mqtt.client.username}")
    public  void setUsername(String username) {
        MqttConfig.username = username;
    }
​
    @Value("${mqtt.client.password}")
    public  void setPassword(String password) {
        MqttConfig.password = password;
    }
}

3、

@AutoConfigureAfter(MqttConfig.class)
public class MqttClientPool {
    static {
        MqttConfig mqttConfig = new MqttConfig();
        //可以获取到配置文件中的信息
    }
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 项目读取 YAML 配置文件的方式与读取 properties 配置文件的方式类似。可以使用 `@ConfigurationProperties` 注解将配置文件的属性与 Java 对象绑定起来,也可以使用 `@Value` 注解逐个读取配置。 以下是使用 `@ConfigurationProperties` 注解读取 YAML 配置文件的示例代码: 1. 创建一个 Java 类,用于存储 YAML 配置文件的属性: ```java @ConfigurationProperties(prefix = "example") public class ExampleProperties { private String name; private int age; //其他属性... //getter和setter方法... } ``` 2. 在 YAML 配置文件定义属性: ```yaml example: name: "Tom" age: 18 #其他属性... ``` 3. 在 Spring Boot 应用程序的配置,启用 `@EnableConfigurationProperties` 注解,并将 `ExampleProperties` 类加入到 Spring 容器: ```java @EnableConfigurationProperties(ExampleProperties.class) @Configuration public class AppConfig { @Bean public ExampleProperties exampleProperties() { return new ExampleProperties(); } } ``` 4. 在需要读取配置的地方,注入 `ExampleProperties` 对象即可使用: ```java @RestController public class ExampleController { @Autowired private ExampleProperties exampleProperties; @GetMapping("/example") public ExampleProperties getExample() { return exampleProperties; } } ``` 以上示例代码使用了 `@ConfigurationProperties` 注解将 YAML 配置文件的属性与 `ExampleProperties` 类绑定起来,并在 Spring Boot 应用程序的配置将 `ExampleProperties` 类加入到 Spring 容器。在需要读取配置的地方,使用 `@Autowired` 注解注入 `ExampleProperties` 对象即可使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值