简体   繁体   中英

How pass and parse json to spring boot standalone application?

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.

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.

You can implement CommandLineRunner to your springboot main class and then prepare Bean like this:

@Bean
public MyInputDto prepareMyInputDto(){
    return new MyInputDto();
}

Then in your run method you can set values from command line argument.

@Override
public void run(String... args) throws Exception {
    MyInputDto bean = context.getBean(MyInputDto.class);
    bean.setMyKey(args[0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM