官术网_书友最值得收藏!

  • Spring Essentials
  • Shameer Kunjumohamed Hamidreza Sattari
  • 125字
  • 2021-07-16 13:05:48

Injecting properties into the Spring environment

Besides the separation of environment-specific configuration using profiles, you would still need to externalize many properties, such as database URLs, e-mails, and date formats in a property file for easier handling. These properties would then either be injected directly into the beans or read from environment by the beans at runtime. Spring's environment abstraction, together with @PropertySource annotation, makes this possible in Spring applications.

The @PropertySource annotation provides a convenient and declarative mechanism for adding a PropertySource to Spring's environment:

@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = "com.springessentialsbook")
public class SpringJavaConfigurator {
...
   @Autowired
   @Lazy
   private SystemSettings systemSettings;

   @Autowired
   private Environment env;

   @Bean
   public SystemSettings getSystemSettings() {
      String dateFormat = env.getProperty("system.date-format");
      String appDisplayName = env.getProperty("app.displayname");

      return new SystemSettings(dateFormat, appDisplayName);
   }
…
}
主站蜘蛛池模板: 秦安县| 武宁县| 靖宇县| 钦州市| 邵东县| 南和县| 蓝山县| 手游| 桦甸市| 宝鸡市| 永吉县| 德州市| 益阳市| 岳普湖县| 醴陵市| 定兴县| 遂昌县| 天台县| 吉林省| 桐庐县| 永寿县| 苗栗县| 西乡县| 曲松县| 镇坪县| 沙雅县| 彭水| 台北县| 香港 | 遂川县| 宜兰市| 鲜城| 府谷县| 荣成市| 河曲县| 宜兰市| 桐柏县| 汾西县| 思茅市| 塔河县| 山丹县|