How to inject properties into a spring bean from Main class

后端 未结 3 1832
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 12:30

I\'m using spring with my application, and I\'m able to inject some properties from some file on a class path into my app and everything works perfectly. i.e.

&         


        
相关标签:
3条回答
  • 2021-01-23 13:07

    I had a similar problem sometime back. My requirement was the the property files is not bundled inside the application (and hence not in classpath). The file could be at any location in file system. Here is how I solved it,

    1. Define an environment variable the value of which points to the location of application.properties.
    2. Lets say we have a env variable APP_PROP_HOME with value /user/home/dir/
    3. Now while defining ServletContextPropertyPlaceholderConfigurer, define the locations as follows

    I am reusing your example

    <bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
            <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
            <property name="searchContextAttributes" value="true" />
            <property name="contextOverride" value="true" />
            <property name="ignoreResourceNotFound" value="true" />
            <property name="locations">
                <list>
                    <value>file://${APP_PROP_HOME}/application.properties</value>
                </list>
            </property>
        </bean>
    

    The Spring resolves ${APP_PROP_HOME} to the value stored in corresponding env property and your application is configured at runtime.

    0 讨论(0)
  • 2021-01-23 13:33

    If I am reading your question correctly, You want to use an external properties file(i.e File is not in the application runtime class path). If that is the case you need to use the file tag

     <value>file:///c:\application.properties</value>
    
    0 讨论(0)
  • 2021-01-23 13:33

    You can use @Value to inject values from the env. Example:

    private someFoo;
    
    @Value("${systemProperties.someFoo}")
    public void setSomeParam(String someParam) {
       this.someFoo = someParam;
    }
    
    0 讨论(0)
提交回复
热议问题