zoukankan      html  css  js  c++  java
  • Spring Boot 环境变量读取 和 属性对象的绑定

    凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的变量。
    如:

    @Configuration
    public class MyWebAppConfigurer implements EnvironmentAware {
    private static final Logger logger = LoggerFactory.getLogger(MyWebAppConfigurer.class);

    private RelaxedPropertyResolver propertyResolver;

    @Value("${spring.datasource.url}")
    private String myUrl;

    /**
    * 这个方法只是测试实现EnvironmentAware接口,读取环境变量的方法。
    */

    @Override
    public void setEnvironment(Environment env) {
    logger.info(env.getProperty("JAVA_HOME"));
    logger.info(myUrl);
    String str = env.getProperty("spring.datasource.url");
    logger.info(str);
    propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    String url = propertyResolver.getProperty("url");
    logger.info(url);
    }
    }

    @Controller @Service 等被Spring管理的类都支持,注意重写的方法 setEnvironment 是在系统启动的时候被执行。
    或者如下Controller:

    @Controller
    public class PageController implements EnvironmentAware{

    @Override
    public void setEnvironment(Environment environment) {
    String s = environment.getProperty("JAVA_HOME");
    System.out.println(s);
    }
    }

    我们还可以通过@ConfigurationProperties 读取application属性配置文件中的属性。

    @Configuration
    @ConditionalOnClass(Mongo.class)
    @EnableConfigurationProperties(MongoProperties.class)
    public class MongoAutoConfiguration {

    @Autowired
    private MongoProperties properties;

    }
    • @ConditionOnClass表明该@Configuration仅仅在一定条件下才会被加载,这里的条件是Mongo.class位于类路径上
    • @EnableConfigurationProperties将Spring Boot的配置文件(application.properties)中的spring.data.mongodb.*属性映射为MongoProperties并注入到MongoAutoConfiguration中。
    • @ConditionalOnMissingBean说明Spring Boot仅仅在当前上下文中不存在Mongo对象时,才会实例化一个Bean。这个逻辑也体现了Spring Boot的另外一个特性——自定义的Bean优先于框架的默认配置,我们如果显式的在业务代码中定义了一个Mongo对象,那么Spring Boot就不再创建。
    @ConfigurationProperties(prefix = "spring.data.mongodb")
    public class MongoProperties {

    private String host;
    private int port = DBPort.PORT;
    private String uri = "mongodb://localhost/test";
    private String database;

    // ... getters/ setters omitted
    }

    它就是以spring.data.mongodb作为前缀的属性,然后通过名字直接映射为对象的属性,同时还包含了一些默认值。如果不配置,那么mongo.uri就是mongodb://localhost/test。

  • 相关阅读:
    一个该不该抽出来的函数引起的思考
    规范代码之方法重用
    web列表分页与问题
    win10系统休眠无法唤醒,无法完全关机问题
    java父子类的初始化顺序--个人总结
    java并发包-concurrentMap和CopyOnWriteArrayList
    大浏览量系统的静态化架构设计
    Angular4 innerHtml呈现富文本内容样式
    Angular4项目运行时URL自动加#方法
    在Angular4中使用ng2-baidu-map详解
  • 原文地址:https://www.cnblogs.com/jpfss/p/8360746.html
Copyright © 2011-2022 走看看