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

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);
   }
…
}
主站蜘蛛池模板: 亚东县| 大荔县| 宿州市| 西安市| 曲周县| 景洪市| 商水县| 林甸县| 虎林市| 同心县| 永仁县| 逊克县| 临泽县| 乌拉特中旗| 海晏县| 桂阳县| 台湾省| 麻城市| 沁源县| 获嘉县| 上饶县| 贵德县| 伊金霍洛旗| 昭平县| 南和县| 永安市| 巴中市| 报价| 宁海县| 绵竹市| 九龙坡区| 饶平县| 米林县| 门头沟区| 克山县| 礼泉县| 巩留县| 土默特左旗| 罗田县| 杨浦区| 屏南县|