How to set dynamically a bean reference in Spring?

后端 未结 6 993
抹茶落季
抹茶落季 2020-12-09 19:56
   
     



  

        
6条回答
  •  长情又很酷
    2020-12-09 20:34

    PropertyPlaceholderConfigurer is the answer, yet I would imagine that you would like this to happen without the need to stay updating your properties file for each environment.

    My suggestion would therefore be as follows

    1. Use PropertyPlaceholderConfigurer, but do not create a properties file
    2. By default, PropertyPlaceholderConfigurer first tries to find a value in a properties file, but if that fails, it will look for one in system properties

    So all you need to do is to define both beans the same way that you are doing it, i.e. dev and stag.. which is a fine approach since you're clearly showing the different configurations... it would help if you also added some alias to show clearly the setting you want to use.

    Next, pass in a system property defining what mode you are in... and ideally explicitly set PropertyPlaceholderConfigurer to use System properties.

    So.. your config would look something like this

    
    
       
         
    
    
    
      
      
      
    
    
    
      
      
      
    
    

    You can then pass in the property upon startup in the following fashion

    -D=
    

    So in this case you'd use

    -Dlaunch.mode=dev_mode
    

    Or

    -Dlaunch.mode=staging_mode
    

    And you won't need to touch any of the configuration files.

    Just a further note on systemPropertiesMode, accepted values are the following:

    • 0 - never look in system properties
    • 1 - use system properties as a fallback (i.e. if not found in properties files)
    • 2 - system properties always override (the mode i'm suggesting)

    Hope it helps :)

    Note: This recommendation is only applicable to Spring < 3.1, since from 3.1 onward, the recommended approach is to use @Profile

提交回复
热议问题