How to read names of all properties and its values from application.properties file in java spring boot app

568 Views Asked by At

I want to read all the values and its key from application.properties file in Java spring boot application.

I can across this article which read values in multiple ways. The problem with this approach is every time you add a property, we need to update the code.

I want a dynamic way to read all keys and values. I do not want to make code changes once a property is added to application.properties file.

I tried something like this and did not got the desired result:

@Autowired
    private Environment environment;

    @GetMapping
    public Map<String, String> getAllProperties() {
        Map<String, String> properties = new HashMap<>();

        // Get all property names
        String[] propertyNames = environment.getProperty("spring.config.name", "application").split(",");
        for (String propertyName : propertyNames) {
            String propertyValue = environment.getProperty(propertyName);
            properties.put(propertyName, propertyValue != null ? propertyValue : "null");
        }

        return properties;
    }

I checked and application.properties file is located under src/main/resources & the file name is application.properties

Let me know if what I am trying to achieve is possible or not.

2

There are 2 best solutions below

6
Jenia On

your properties are in resources, writing to resources is a bad idea

Of course, you can write a separate method that will read from the properties file, but you will have problems when you build your project in war or jar

Create a hidden folder and put whatever you want there

0
Toni On

Try with the following code:

PropertySource<?> propertySource =
    ((AbstractEnvironment) environment)
        .getPropertySources().stream()
            .filter(i -> i instanceof OriginTrackedMapPropertySource)
            .filter(i -> i.getName().contains("application.properties"))
            .findFirst()
            .orElseThrow();
Map<String, String> properties = (Map<String, String>) propertySource.getSource();

Environment bean contains all property sources, but it needs to be cast to AbstractEnvironment to access property sources directly. Then those should be filtered to remain only OriginTrackedMapPropertySources.

Finally, filter property sources by name containing the file name. The reason why the contains is used is that the names of remaining property sources are in the following format:

Config resource 'class path resource [application.properties]' via location 'optional:classpath:/'

Remember that those properties are the original values from the file, but can be overridden by, for example, profile-specific properties. In that case, environment.getProperty(propertyName) would return a different value than one read from the code above.

For reference: Access all Environment properties as a Map or Properties object