spring 如何使用 application.properties 传递 Map<String, String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26275736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:07:35  来源:igfitidea点击:

How to pass a Map<String, String> with application.properties

springspring-boot

提问by Marco

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

我已经在需要配置的 web 服务中实现了一些授权。

Currently the user/password combo is hardcoded into the bean configuration. I would like to configure the map with users and passwords into the application.properties so the configuration can be external.

目前,用户/密码组合被硬编码到 bean 配置中。我想使用用户和密码将地图配置到 application.properties 中,以便配置可以是外部的。

Any clue on how this can be done?

关于如何做到这一点的任何线索?

<bean id="BasicAuthorizationInterceptor" class="com.test.BasicAuthAuthorizationInterceptor">
    <property name="users">
        <map>
            <entry key="test1" value="test1"/>
            <entry key="test2" value="test2"/>
        </map>
    </property>
</bean>

采纳答案by M. Deinum

A java.util.Propertiesobject is already a Map, actually a HashTablewhich in turn implements Map.

一个java.util.Properties对象已经是 a Map,实际上是 a HashTable,而后者又实现了Map

So when you create a properties file (lets name it users.properties) you should be able to load it using a PropertiesFactoryBeanor <util:properties />and inject it into your class.

因此,当您创建一个属性文件(让我们为其命名users.properties)时,您应该能够使用PropertiesFactoryBeanor加载它<util:properties />并将其注入到您的类中。

test1=test1
test2=test2

Then do something like

然后做类似的事情

<util:properties location="classpath:users.properties" id="users" />

<bean id="BasicAuthorizationInterceptor" class="com.test.BasicAuthAuthorizationInterceptor">
    <property name="users" ref="users" />
</bean>

Although if you have a Map<String, String>as a type of the users property it might fail... I wouldn't put them in the application.propertiesfile. But that might just be me..

虽然如果你有一个Map<String, String>作为用户属性的类型,它可能会失败......我不会把它们放在application.properties文件中。但这可能只是我..

回答by Marcos Nunes

you can use @Value.

你可以使用@Value.

Properties file:

属性文件:

users={test1:'test1',test2:'test2'}

Java code:

爪哇代码:

@Value("#{${users}}")
private Map<String,String> users;

回答by Andy Wilkinson

You can use @ConfigurationPropertiesto have values from application.propertiesbound into a bean. To do so you annotate your @Beanmethod that creates the bean:

您可以使用@ConfigurationProperties将值从application.properties绑定到 bean 中。为此,您可以注释@Bean创建 bean 的方法:

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

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

作为 bean 初始化的一部分,任何属性 onBasicAuthAuthorizationInterceptor都将根据应用程序的环境进行设置。例如,如果这是您的 bean 的类:

public class BasicAuthAuthorizationInterceptor {

    private Map<String, String> users = new HashMap<String, String>();

    public Map<String, String> getUsers() {
        return this.users;
    }
}

And this is your application.properties:

这是您的 application.properties:

users.alice=alpha
users.bob=bravo

Then the usersmap will be populated with two entries: alice:alphaand bob:bravo.

然后users地图将填充两个条目:alice:alphabob: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<String, String> users = new HashMap<String, String>();

        public Map<String, String> getUsers() {
            return this.users;
        }
    }
}

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

查看javadoc 以ConfigurationProperties获取有关其各种配置选项的更多信息。例如,您可以设置前缀将您的配置划分为多个不同的命名空间:

@ConfigurationProperties(prefix="foo")

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

要使绑定生效,您必须在 application.properties 中声明的属性上使用相同的前缀:

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

回答by Paul Phoenix

I think you are looking for something similar

我想你正在寻找类似的东西

http://www.codejava.net/frameworks/spring/reading-properties-files-in-spring-with-propertyplaceholderconfigurer-bean

http://www.codejava.net/frameworks/spring/reading-properties-files-in-spring-with-propertyplaceholderconfigurer-bean

You can pick values from .properties similarly and assign it to your map.

您可以类似地从 .properties 中选择值并将其分配给您的地图。