美文网首页
通过Environment对象获取配置

通过Environment对象获取配置

作者: 黑曼巴yk | 来源:发表于2020-10-05 21:22 被阅读0次

    简介

    通过Autowired注入Spring的Environment对象。并且通过该对象的getRequiredProperty("key") 方法可以获取到配置文件中对应 key 的 value。

    代码

    使用如下

    import org.springframework.core.env.Environment;
    
    @Configuration
    public class JpaConfig {
    
        @Autowired
        private Environment environment;
    
        /*
         * 从 application.yml 中读取 hibernate 相关配置
         */
        private Properties jpaProperties() {
            Properties properties = new Properties();
            properties.put("hibernate.dialect", environment.getRequiredProperty("datasource.sampleapp.hibernate.dialect"));
            properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("datasource.sampleapp.hibernate.hbm2ddl.auto"));
            properties.put("hibernate.show_sql", environment.getRequiredProperty("datasource.sampleapp.hibernate.show_sql"));
            properties.put("hibernate.format_sql", environment.getRequiredProperty("datasource.sampleapp.hibernate.format_sql"));
            if (StringUtils.isNotEmpty(environment.getRequiredProperty("datasource.sampleapp.defaultSchema"))) {
                properties.put("hibernate.default_schema", environment.getRequiredProperty("datasource.sampleapp.defaultSchema"));
            }
            return properties;
        }
    }
    

    相关文章

      网友评论

          本文标题:通过Environment对象获取配置

          本文链接:https://www.haomeiwen.com/subject/ocfzuktx.html