Learn Java under the main method parameters args

The following example to do a project with a spring boot:

This is a spring boot start classes

public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

Args parameter can see its main method.

Then if we want to pass parameters when a project starts to the main method, and then do the appropriate logic according to different parameters, to be an example of mass participation of the following:

public class SpringbootApplication {
    public static void main(String[] args) {
        //打印出参数
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

I use the development tool is idea, the next parameter is set to be a start:

  1. Click to go to modify the configuration

Here Insert Picture Description

  1. Set the parameters for hello world
    Here Insert Picture Description
    to start the project, look at the effect:
    Here Insert Picture Description
    you can see the parameters hello world to be printed out, that argument successfully entered the main method that starts class, then you can set the parameters according to business needs

to sum up

You know, the main method is to identify and called the virtual machine, developers can not manually invoke the main method, so if you really need to pass parameters in the main method, by the above method is able to do, of course, by this java xxx hello world the effect is the same command line, do Sao operating in this way, it is also possible to start encryption, such as this play:

public class SpringbootApplication {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
        //校验是不是admin的用户
        if (!"admin".equals(args)) {
            throw new Exception();
        }
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

Start'll get an error:
Here Insert Picture Description
In conclusion, anyway, there is reasonable, look no problem.

Published 289 original articles · won praise 302 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_38106322/article/details/104947867