springboot中非容器类获取配置文件数据

如果是被spring容器所管理,一般采用@Value注解就可以读取到application.yml文件的内容。

但是不被spring容器管理,使用@Value是无效的。注入时会是NULL。但就是会有这样的场景,此时可采用在springboot启动类中将环境注入到某一个公共配置类,该类所有属性为公共静态属性攻外部类直接使用。

@SpringBootApplication
public class DemoStarterTestApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(DemoStarterTestApplication.class, args);
        ConfigurableEnvironment environment = run.getEnvironment();
        String address = environment.getProperty("server.address1");
        int age = Integer.parseInt(environment.getProperty("spring.user.age"));
        EnvConfig envConfig = new EnvConfig();
        envConfig.setAddress(address);
        envConfig.setAge(age);

        System.out.println("地址为"+EnvConfig.address+",年龄为"+EnvConfig.age);
    }

}

公共配置类

public class EnvConfig {
    public static String address;

    public static int age;

    public  void setAddress(String address) {
        EnvConfig.address = address;
    }

    public  void setAge(int age) {
        EnvConfig.age = age;
    }
    
}

配置文件

猜你喜欢

转载自blog.csdn.net/weixin_42740540/article/details/124348851