Mastering JSON Configuration in Spring Boot 3: From CLI to Custom Property Sources

This article explains multiple ways to load JSON configuration into Spring Boot 3 applications, covering command‑line arguments, @PropertySource with custom factories, ApplicationContextInitializer, nested JSON handling, and direct @Bean approaches, complete with code examples and troubleshooting tips.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering JSON Configuration in Spring Boot 3: From CLI to Custom Property Sources

Environment: Spring Boot 3.4.0

1. Introduction

Spring Boot can load JSON configuration files via @ConfigurationProperties, binding a JSON file to a configuration class. It also supports providing JSON data through the spring.application.json property or SPRING_APPLICATION_JSON environment variable, giving developers and operators flexible configuration options.

2. Practical Cases

2.1 Load JSON from the command line

Any property named spring.application.json or the SPRING_APPLICATION_JSON environment variable is parsed and added to the application environment at startup.

$ SPRING_APPLICATION_JSON="{\"pack\":{\"title\":\"xxxooo\"}}" java -jar myapp.jar

The above makes pack.title=xxxooo available in the Spring environment.

Loading JSON via system property:

java -Dspring.application.json="{\"pack\":{\"title\":\"xxxooo\"}}" -jar load_json-1.0.0.jar

Loading JSON via command‑line argument:

java -jar load_json-1.0.0.jar --spring.application.json="{\"pack\":{\"title\":\"xxxooo\"}}"

These simple methods work but lack scalability for large JSON payloads.

2.2 Load JSON with @PropertySource

Define a configuration class:

public class JsonProperties {
    private Integer port;
    private String host;
    // getters, setters
}

Create a JSON file configprops.json:

{
  "port": 6666,
  "host": "127.0.0.1"
}

Annotate the class:

@Component
@PropertySource("classpath:configprops.json")
@ConfigurationProperties
public class JsonProperties {}

When the application starts, an error occurs due to an extra comma. To fix it, implement a custom PropertySourceFactory:

public class JsonPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
        return new MapPropertySource("json-property", readValue);
    }
}

Update the annotation:

@Component
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
@ConfigurationProperties
public class JsonProperties {}

Application output shows the JSON file was read successfully.

Error screenshot
Error screenshot
Success screenshot
Success screenshot

2.3 Nested JSON structures

For nested JSON, map the nested object to a Map field:

@Component
@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class)
@ConfigurationProperties
public class JsonProperties {
    private Integer port;
    private String host;
    private LinkedHashMap<String, ?> pack;
}

The pack node is bound to the LinkedHashMap.

2.4 Use ApplicationContextInitializer

For full control, implement a custom ApplicationContextInitializer that reads the JSON file and adds each entry as a property with a custom. prefix.

public class JsonPropertyContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    private static final String CUSTOM_PREFIX = "custom.";
    @Override
    public void initialize(ConfigurableApplicationContext ctx) {
        try {
            Resource resource = ctx.getResource("classpath:configprops.json");
            Map<String, Object> map = new ObjectMapper().readValue(resource.getInputStream(), Map.class);
            map.forEach((k, v) -> ctx.getEnvironment().getPropertySources()
                .addFirst(new MapPropertySource(CUSTOM_PREFIX + k, Collections.singletonMap(CUSTOM_PREFIX + k, v))));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Inject the properties with @Value("${custom.port}") and @Value("${custom.host}").

2.5 Direct Bean definition

Read the JSON file with ObjectMapper in a @Bean method:

@Configuration
public class AppConfig {
    @Bean
    public AppProperties appProperties() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(new ClassPathResource("configprops.json").getInputStream(), AppProperties.class);
    }
}

This completes all methods for loading JSON configuration in Spring Boot.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaSpring BootApplicationContextInitializerJSON configurationPropertySource
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.