How to pass a Map with application.properties

后端 未结 4 1327
失恋的感觉
失恋的感觉 2020-12-14 08:29

I have implemented some authorization in a webservice that needs be configured.

Currently the user/password combo is hardcoded into the bean configuration. I would l

4条回答
  •  执笔经年
    2020-12-14 09:02

    You can use @ConfigurationProperties to have values from application.properties bound into a bean. To do so you annotate your @Bean method that creates the bean:

    @Bean
    @ConfigurationProperties
    public BasicAuthAuthorizationInterceptor interceptor() {
        return new BasicAuthAuthorizationInterceptor();
    }
    

    As part of the bean's initialisation, any property on BasicAuthAuthorizationInterceptor will be set based on the application's environment. For example, if this is your bean's class:

    public class BasicAuthAuthorizationInterceptor {
    
        private Map users = new HashMap();
    
        public Map getUsers() {
            return this.users;
        }
    }
    

    And this is your application.properties:

    users.alice=alpha
    users.bob=bravo
    

    Then the users map will be populated with two entries: alice:alpha and bob:bravo.

    Here's a small sample app that puts this all together:

    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableAutoConfiguration
    @EnableConfigurationProperties
    public class Application {
    
        public static void main(String[] args) throws Exception {
            System.out.println(SpringApplication.run(Application.class, args)
                    .getBean(BasicAuthAuthorizationInterceptor.class).getUsers());
        }
    
        @Bean
        @ConfigurationProperties
        public BasicAuthAuthorizationInterceptor interceptor() {
            return new BasicAuthAuthorizationInterceptor();
        }
    
        public static class BasicAuthAuthorizationInterceptor {
    
            private Map users = new HashMap();
    
            public Map getUsers() {
                return this.users;
            }
        }
    }
    

    Take a look at the javadoc for ConfigurationProperties for more information on its various configuration options. For example, you can set a prefix to divide your configuration into a number of different namespaces:

    @ConfigurationProperties(prefix="foo")
    

    For the binding to work, you'd then have to use the same prefix on the properties declared in application.properties:

    foo.users.alice=alpha
    foo.users.bob=bravo
    

提交回复
热议问题