6

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 ?

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311

4 Answers4

35

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" />
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

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.

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
1

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>
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
-1

Using enumeration to loop through Properties

Jack47
  • 194
  • 1
  • 8