JCommander를 통한 JAR 실행 Parameter 관리 > 질문답변

본문 바로가기

사이트 내 전체검색

뒤로가기 질문답변

JCommander를 통한 JAR 실행 Parameter 관리

페이지 정보

작성자 미친새 작성일 21-04-02 23:16 조회 7,167 댓글 0

본문

Java를 이용해서 JAR를 만든 후에 JAR를 직접 실행할 경우 Parameter를 넣어주어야 되는 경우가 있다. 예를 들어서 아래와 같은 JAR 파일에 Parameter로 무언가를 보낸다고 가정을 해보면,

$ java jar Test.jar param1 param2 param3
위와 같은 방식으로 기본적으로 넘길 수 있을 것이다. 이 경우에는 main 함수에서 대게 args에 대한 처리를 해주어야 한다.

public static void main(String[] arg) {
if (arg.length < 3) {
System.err.println("Usage: java jar Test.jar param1 param2 param3");
System.exit(1);
}
}
하지만 JCommander를 쓸 경우는 이러한 Argument 작업을 더욱 쉽고 직관적으로 할 수 있다.

<properties>
<jcommander.version>1.48</jcommander.version>
</properties>

<dependencies>
<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
<version>${jcommander.version}</version>
</dependency>
</dependencies>
예를 들어서 DB 접속을 위해서 host, port, username, password를 실행 Parameter로 받는다고 가정을 해보자.



import com.beust.jcommander.Parameter;

public class DatabaseArgs {
public static final String HELP = "--help";
@Parameter(names = HELP, description = "Display usage information", help = true)
private boolean help;

public boolean getHelp() {
return help;
}

public static final String HOST = "--host";
@Parameter(names = HOST, description = "The endpoint of Database", required = true)
private String host;

public String getHost() {
return Host;
}

public static final String PORT = "--port";
@Parameter(names = PORT, description = "The port of Database", required = true)
private String port;

public String getPort() {
return port;
}

public static final String USERNAME = "--username";
@Parameter(names = USERNAME, description = "The username of Database", required = true)
private String username;

public String getUsername() {
return username;
}

public static final String PASSWORD = "--password";
@Parameter(names = PASSWORD, description = "The password of Database", required = true)
private String password;

public String getPassword() {
return password;
}
}
위와 같이 Class를 생성하면 실행시 "--help" 옵션을 주게 되면 사용법이 자동으로 나오게 된다. Parameter Annotation을 통해서 required로 지정된 Parameter의 경우 필수 옵션이기 때문에 넣지 않게 되면은 Exception이 발생하게 된다.

com.beust.jcommander.ParameterException: The following options are required: --password --username --host --port
Usage: <main class> [options]
  Options:
    --help
      Display usage information
      Default: false
  * --host
      The endpoint of Database
  * --password
      The password of Database
  * --port
      The port of Database
  * --username
      The username of Database
그 다음은 위의 Parameter들을 사용하여 실행하는 Class가 있을 경우 아래와 같이 구현하면 된다.

public static void main(String[] args) {
DatabaseArgs params = new DatabaseArgs();
JCommander cmd = new JCommander(params);

try {
// Parse given arguments
cmd.parse(args);

// Show usage information if help flag exists
if (params.getHelp()) {
cmd.usage();
return;
}

// Get Database information
String host = params.getHost();
String port = params.getPort();
String username = params.getUsername();
String password = params.getPassword();
} catch (ParameterException e) {
JCommander.getConsole().println(e.toString());
cmd.usage();
}
}
위와 같이 Class가 준비되었을 경우 Jar를 실행시 아래와 같이 Parameter를 넘기면 된다.

$ java jar Test.jar --host db.databasehost.com --port 3306 --username myuser --password mypassword
참고:

[1] JCommander: http://jcommander.org/



출처: https://skysince.tistory.com/13 [그래도 개발자일 때 좋았다]

첨부파일

댓글목록 0

등록된 댓글이 없습니다.

Copyright © 소유하신 도메인. All rights reserved.

사이트 정보

회사명 : 회사명 / 대표 : 대표자명
주소 : OO도 OO시 OO구 OO동 123-45
사업자 등록번호 : 123-45-67890
전화 : 02-123-4567 팩스 : 02-123-4568
통신판매업신고번호 : 제 OO구 - 123호
개인정보관리책임자 : 정보책임자명

PC 버전으로 보기