简介
通过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;
}
}
网友评论