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

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);
   }
…
}
主站蜘蛛池模板: 汽车| 平塘县| 石棉县| 耒阳市| 大石桥市| 滦平县| 景东| 靖边县| 广丰县| 望都县| 通海县| 高阳县| 攀枝花市| 宝鸡市| 桐柏县| 贞丰县| 五台县| 公安县| 华坪县| 东光县| 红桥区| 远安县| 宜昌市| 韶山市| 鹤山市| 米易县| 上林县| 毕节市| 东莞市| 通海县| 正定县| 牙克石市| 通化县| 海门市| 盱眙县| 乾安县| 察隅县| 保靖县| 汤阴县| 静乐县| 沁阳市|