In my Java class I have a field of type, say, java.util.Properties or java.util.Map. I'd like Spring to inject the field with all properties which start with the given prefix. Ideally by specifying wildcard in the property annotation, smth like @Value(${prefix.*})
that doesn't seem to work unfortunately.
How can I achieve that?
AFAIK there isn't a direct way to achieve what you are looking for.
You can however use Spring EL
in combination with custom implementation of org.springframework.core.io.support.PropertiesLoaderSupport
.
First extend the PropertiesLoaderSupport ( or any of it's subclass ). Introduce a method ( say filterProps ), which will return java.util.Properties
object with filtered properties, such as below
public class CustomPropertyLoader extends PropertiesLoaderSupport {
public Properties filterProperties(String prefix){
Properties temp = new Properties();
for(Properties props : this.localProperties){
/*
* Iterate over props and filter them as
* per prefix (or any custom logic) to temp
*/
}
return temp;
}
}
TIP - You can use a regex for more generic scenarios instead of String
as method argument.
Second define a corresponding bean of above class
<bean id="customPropertyLoader" class="x.y.z.CustomPropertyLoader">
<property name="locations" value="classpath*:/**/some*.properties"/>
</bean>
Last annotate the field of type java.util.Properties
in your class as @Value(#{customPropertyLoader.filterProperties('prefix.*')})
PS : Please excuse any compilation / syntax error as I haven't compiled and check the setup; but it should work. In case not, let know in comments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.