キーが個別のプレフィックスで始まるすべてのプロパティ(たとえば、「log4j.appender。」で始まるすべてのプロパティ)を取得する必要があり、次のコードを記述しました(Java 8のストリームとラムダを使用)。
public static Map<String,Object> getPropertiesStartingWith( ConfigurableEnvironment aEnv,
String aKeyPrefix )
{
Map<String,Object> result = new HashMap<>();
Map<String,Object> map = getAllProperties( aEnv );
for (Entry<String, Object> entry : map.entrySet())
{
String key = entry.getKey();
if ( key.startsWith( aKeyPrefix ) )
{
result.put( key, entry.getValue() );
}
}
return result;
}
public static Map<String,Object> getAllProperties( ConfigurableEnvironment aEnv )
{
Map<String,Object> result = new HashMap<>();
aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
return result;
}
public static Map<String,Object> getAllProperties( PropertySource<?> aPropSource )
{
Map<String,Object> result = new HashMap<>();
if ( aPropSource instanceof CompositePropertySource)
{
CompositePropertySource cps = (CompositePropertySource) aPropSource;
cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
return result;
}
if ( aPropSource instanceof EnumerablePropertySource<?> )
{
EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) );
return result;
}
myLog.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName()
+ " and cannot be iterated" );
return result;
}
private static void addAll( Map<String, Object> aBase, Map<String, Object> aToBeAdded )
{
for (Entry<String, Object> entry : aToBeAdded.entrySet())
{
if ( aBase.containsKey( entry.getKey() ) )
{
continue;
}
aBase.put( entry.getKey(), entry.getValue() );
}
}
開始点は、埋め込まれたPropertySourceを返すことができるConfigurableEnvironmentであることに注意してください(ConfigurableEnvironmentはEnvironmentの直接の子孫です)。次の方法で自動配線できます。
@Autowired
private ConfigurableEnvironment myEnv;
非常に特殊な種類のプロパティソース(通常、Springの自動構成では使用されないJndiPropertySourceなど)を使用しない場合は、環境に保持されているすべてのプロパティを取得できます。
実装は、Spring自体が提供する反復順序に依存し、最初に見つかったプロパティを取得します。後で見つかった同じ名前のプロパティはすべて破棄されます。これにより、環境がプロパティを直接要求された場合と同じ動作が保証されます(最初に見つかったプロパティを返します)。
$ {...}演算子を使用したエイリアスが含まれている場合、返されるプロパティはまだ解決されていないことにも注意してください。特定のキーを解決したい場合は、環境に直接問い合わせる必要があります。
myEnv.getProperty( key );