Reputation: 47300
Normally i would populate a field using annotations when I knew the property name like so :
@Value("${myproperties.myValue}")
private String myString
However I now want to loop through all the properties in a file, when their names are unknown, and store both there value and name. What's the best way with spring and java ?
Upvotes: 7
Views: 42313
Reputation: 136112
Actually if you need only to read properties from a file and not to use these properties in Spring's property placeholders, then the solution is simple
public class Test1 {
@Autowired
Properties props;
public void printProps() {
for(Entry<Object, Object> e : props.entrySet()) {
System.out.println(e);
}
}
...
<util:properties id="props" location="/spring.properties" />
Upvotes: 37
Reputation: 136112
I could not find a simpler solution than this
class PropertyPlaceholder extends PropertyPlaceholderConfigurer {
Properties props;
@Override
protected Properties mergeProperties() throws IOException {
props = super.mergeProperties();
return props;
}
}
public class Test1 {
@Autowired
PropertyPlaceholder pph;
public void printProps() {
for(Entry<Object, Object> e : pph.props.entrySet()) {
System.out.println(e);
}
}
...
...
<bean class="test.PropertyPlaceholder">
<property name="locations">
<value>/app.properties</value>
</property>
</bean>
Upvotes: 1
Reputation: 299178
The @Value
mechanism works through the PropertyPlaceholderConfigurer
which is in turn a BeanFactoryPostProcessor
. The properties used by it are not exposed at runtime. See this previous answer of mine for a possible solution.
Upvotes: 1