How pass and parse json to spring boot standalone application?

728 Views Asked by At

For example:

java -jar mySpringApplication --myJsonParameter="{\"myKey\":\"myValue\"}"

This should be resolved like that:

public class MyService {
    @Autowired
    //or @Value("myJsonParameter") ? 
    private MyInputDto myInputDto;
}

public class MyInputDto {
    private String myKey;
}

The idea is to pass named parameter from command line (and following spring externalization practics) but inject Typed value parsed from json, not string.

1

There are 1 best solutions below

0
On

You can try using property spring.application.json and annotate your MyInputDto as @org.springframework.boot.context.properties.ConfigurationProperties.

Start your application like this:

java -Dspring.application.json='{"myKey":"myValue"}' -jar mySpringApplication.jar

Implementing your service:

@EnableConfigurationProperties(MyInputDto.class)
public class MyService {

    @Autowired
    private MyInputDto myInputDto;

    // use myInputDto.getMyKey();

}

@ConfigurationProperties
public class MyInputDto {
    private String myKey;

    public String getMyKey() { return this.myKey; }

    public void setMyKey(String myKey) { this.myKey = myKey; }
}

See Spring external configuration documentation for more information.