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

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);
   }
…
}
主站蜘蛛池模板: 九龙城区| 包头市| 汉阴县| 丹阳市| 克山县| 呼伦贝尔市| 边坝县| 永登县| 茂名市| 灌云县| 鄂托克前旗| 三江| 吴桥县| 江北区| 怀柔区| 平舆县| 盖州市| 连平县| 普兰县| 乐亭县| 黄梅县| 山丹县| 高清| 蛟河市| 乾安县| 平武县| 澳门| 德清县| 桐城市| 武陟县| 怀安县| 涡阳县| 寻乌县| 炎陵县| 通许县| 从化市| 廉江市| 浮梁县| 大洼县| 个旧市| 抚州市|