Access properties file programmatically with Spring?

前端 未结 15 1648
说谎
说谎 2020-11-27 09:37

We use the code below to inject Spring beans with properties from a properties file.



        
15条回答
  •  無奈伤痛
    2020-11-27 09:53

    You can get your properties through Environment class. As documentation stands:

    Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them.

    Having Environment as a env variable, simply call:

    env.resolvePlaceholders("${your-property:default-value}")
    

    You can get your 'raw' properties through:

    env.getProperty("your-property")
    

    It will search through all properties source that spring has registered.

    You can either obtain Environment through:

    • inject ApplicationContext by implementing ApplicationContextAware and then call getEnvironment() on context
    • implement EnvironmentAware.

    It's obtain through implementation of a class because properties are resolved on early stage of application startup, as they may be required for bean construction.

    Read more on documentation: spring Environment documentation

提交回复
热议问题