If you use the framework Spring to do dependency injection and manage your Beans, you can decouple your code from searching command lines and simply inject read values from the environment.
Example:
@Component
public class MeuComponente {
@Value("${usuario}")
private String usuario;
}
See the documentation and you will see that the injected values are read from several sources, the first being the command line arguments, but also including Java system properties (system properties), environment variables and Spring configuration file.
This approach is flexible and makes it easy to test components individually, as well as allowing multiple system configuration mechanisms. For example, the user can set the database as an environment variable, while the password is passed via command line argument and other default settings are set in the file application.properties
that goes along with the system.
And if at any time you need to access the arguments more directly, just inject ApplicationArguments
. Example:
@Component
public class MeuComponente {
@Autowired
public MeuComponente(ApplicationArguments args) {
List<String> dbs = arg.getOptionValues("DB");
if (!dbs.isEmpty()) {
carregaDB(dbs.get(0));
}
}
}
Of course, if you want to accept arguments more elaborately as in native programs of the operating system, it is better to use another library (as cited in the reply of @Maniero), although my general recommendation would simply be not to use Java.
In the
main
you can pass several arguments, precisely why it takes a string array.– user28595
Here is some material that can help (as long as no one gives an appropriate answer): http://stackoverflow.com/questions/367706/how-to-parse-command-line-arguments-in-java
– Luiz Vieira
Ex.:
public static void main(String args[])
in thatargs[]
is where you will handle the expected arguments(in your case, user and password) within your code. That’s what you want to do?– user28595
This I know, I want an easy and readable way to do this.
– HagaHood