jenkins로 배치를 실행하는 시점에 특정 클래스를 구동하고 싶을 때 CommandLineRunner를 사용하여 구현하면 수행이 가능하다.
이렇게 애플리케이션 구동 시점에 특정 코드를 구현시키기 위해 제공하는 인터페이스는 두가지가 있다.
1. CommandLineRunner
2. ApplicationRunner
기본 코드는 아래와 같다.
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class DemoCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner Args: " + Arrays.toString(args));
}
}
등록시에는 @Component annotation을 선언하여 수행이 가능하게끔 해주면 된다.
CommandLineRunner의 경우 String args로 args[]로 특정 값을 받아 실행이 가능하다.
ApplicationRunner 의 경우에도 크게 다른 부분은 없지만 parameter가 String이 아닌ApplicationArguments 타입으로 인자를 받아 처리가 가능하다.
만약 CommanLineRunner나 ApplicationRunner 를 다중으로 수행하여야 할때 순서를 정리하고 싶다면 @Order annotation으로 순서를 정해줄 수 도 있다.
jenkins에서 인자를 호출받아 특정 클래스를 수행시켜 주고 싶다면 아래와 같이 구현이 가능하다.
@Component
@RequiredArgsConstructor
public class BatchCommandLineRunner implements CommandLineRunner {
private final ApplicationContext context;
@Override
public void run(String... args) {
Map<String, BatchJob> jobs = context.getBeansOfType(BatchJob.class);
//실행시킬 특정 클래스명을 인자로 받는다.
final String className = args[0];
//Batchjob은 interface로 해당 클래스를 implement해서 구현하였고 run()
//메서드를 실행하여 그에 맞는 클래스가 수행되도록 한다.
jobs.entrySet().stream()
.filter(job -> job.getKey().equals(className))
.findFirst()
.ifPresent(jobEntry -> {
BatchJob batchJob = jobEntry.getValue();
//CommandLineRunner에서 인자로 받은 String args에서 클래스명을 제외한 내용을 저장한다.
List<String> arguments = Arrays.stream(args).skip(1).collect(Collectors.toList());
String argumentString = Joiner.on(" ").join(arguments);
int result = -1;
try {
//특정 클래스의 run()메서드가 실행되도록 한다.
result = batchJob.run(arguments);
} catch (Exception e) {
e.printStackTrace();
System.exit(result);
}
System.exit(result);
});
System.exit(-1);
}
}
'Spring' 카테고리의 다른 글
The bean 'exampleService.FeignClientSpecification' could not be registered (0) | 2023.05.17 |
---|