小编典典

以Map或Properties对象访问所有Environment属性

spring

我正在使用注释来配置我的spring环境,如下所示:

@Configuration
...
@PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer 
{
    @Autowired
    Environment env;
}

这导致我的财产default.properties成为的一部分Environment。我想在@PropertySource这里使用该机制,因为它已经可以根据环境设置(例如config_dir位置)通过多个后备层和不同的动态位置来重载属性。我只是剥离了后备,以使示例更容易。

但是,现在的问题是我想在中配置数据源属性default.properties。你可以将设置传递给数据源,而无需详细了解数据源期望使用什么设置

Properties p = ...
datasource.setProperties(p);

但是,问题是,Environment对象既不是Properties对象,也不是对象,也不是Map任何可比较的对象。从我的角度来看,这是根本不可能的访问环境的所有值,因为没有keySet或iterator方法或任何可比性。

Properties p <=== Environment env?

我想念什么吗?是否可以通过Environment某种方式访问对象的所有条目?如果是,我可以将条目映射到Map或Properties对象,甚至可以通过前缀过滤或映射它们-将子集作为标准Java创建Map…这就是我想要做的。有什么建议么?


阅读 1207

收藏
2020-04-11

共1个答案

小编典典

你需要类似的东西,也许可以改进。这是第一次尝试:

...
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
...

@Configuration
...
@org.springframework.context.annotation.PropertySource("classpath:/config/default.properties")
...
public class GeneralApplicationConfiguration implements WebApplicationInitializer 
{
    @Autowired
    Environment env;

    public void someMethod() {
        ...
        Map<String, Object> map = new HashMap();
        for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
            PropertySource propertySource = (PropertySource) it.next();
            if (propertySource instanceof MapPropertySource) {
                map.putAll(((MapPropertySource) propertySource).getSource());
            }
        }
        ...
    }
...

基本上,环境的所有内容MapPropertySource(并且有很多实现)都可以作为Map属性来访问。

2020-04-11