If you use the Spring framework to do dependency injection and manage your beans, you can decouple your code from doing searches on command lines and simply inject values read from the environment.
Example:
@Component
public class MeuComponente {
@Value("${usuario}")
private String usuario;
}
See documentation and you'll see that injected values are read from a variety of sources, the first being command-line arguments, but also including Java's system properties, environment variables, and the 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 the command line argument and other default settings are defined in the application.properties
file that goes along with the system.
And if at any point 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 than in native operating system programs, it's better to use another library (like the one cited in the @bigown response), although my general recommendation would be simply do not use Java.