shortcut for injecting strings with spring

前端 未结 3 2338
刺人心
刺人心 2021-02-20 01:01

I inject Strings in my spring config by doing the following:


    

        
3条回答
  •  深忆病人
    2021-02-20 01:17

    You should not have String beans. Just use their value directly.

    Create a properties file strings.properties and put it on the classpath

    strings.key=Region
    

    Declare a PropertyPlaceholderConfigurer

    
        
            strings.properties
        
    
    

    Then annotate instance field Strings as

    @Value("${strings.key}")
    private String key;
    

    Spring will inject the value from the strings.properties file into this key String.

    This obviously assumes that the class in which the @Value annotation appears is a bean managed in the same context as the PropertyPlaceholderConfigurer.

提交回复
热议问题