I tried Spring Batch

Overview

I will keep a memorandum when using Spring Batch with STS. Mainly for myself. Spring Batch is a batch application framework based on the Spring Framework.

The development environment is as follows. OS : Windows 7 Home Edition 64bit Java : JavaSE 8 update 181 Spring Boot : 2.3.4 STS : 4.6.1

STS setup

For the STS setup, I referred to My memorandum.

Creating a project

Click Create new Spring Starter Project below. createProject.PNG

Set the project. NewSpringStarterProject.PNG

Set the library reference. dependencies.PNG

Site info is set, no change. siteInfo.PNG

The project is ready. ProjectExplorer.PNG

Notes

About Lombok

Only Lombok downloads the jar and Select and install the STS used in the installer. The installer can be downloaded from Lombok Official. Since Lombok refers to the project, Using annotations doesn't cause a compile error, getter / setter, constructor is not automatically generated, Attempting to call them will result in a compilation error. Since getter / setter etc. need to be automatically generated by the IDE, You also need to install it on STS.

Installing the Oracle Driver

DB is not used in this article, The configuration of Spring Boot + Spring Batch assumes the use of DB. Therefore, in application.properties and application.yml DB connection information is not listed, In the first place, there is no Oracle Driver When you run the application Cannot run with error that __datasource is required. __ Therefore, to Oracle that was set up on the PC that was confirmed to work I am referencing the library so that I can connect. Also, it can be executed without starting __DB at runtime __. If you have a library and you have a configuration and settings that try to connect to the DB schema That's OK.

Creating a batch application

Spring Batch official get started is here. In the above case, it is a specification to execute the created jar and load the csv data into the DB table.

In this article, I'll try scheduling batch processing without using cron. I referred to Spring Batch scheduling tasks @Scheduled documentation.

As an example, let's create a bean and implement a process to log its contents. Refer to Lombok to omit the variable declaration for log output and the boilerplate of the Bean class.

The implemented class is as follows.

First, the class with @SpringBootApplication, This class is specified at runtime.

BatchSampleApplication.java


package jp.co.illmatics;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BatchSampleApplication {

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

}

This is the main routine for batch processing. By specifying @EnableScheduling Batch scheduling is now possible The method that specified @Scheduled cron = "${cron.pattern1}" It will be executed at the timing specified in.

Batch.java


package jp.co.illmatics;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import jp.co.illmatics.bean.Member;
import jp.co.illmatics.enumeration.VoicePart;
import lombok.extern.slf4j.Slf4j;

@Configuration
@EnableScheduling
@Slf4j
public class Batch {

	private String firstName = "Dummy";
	private String familyName = "Family";
	private String part = VoicePart.LEAD_VOCAL.toString();
	private String birthday = "1991/01/01";

	@Scheduled(cron = "${cron.pattern1}")
	public void execute() {
		Member member = new Member(firstName, familyName, part, birthday);
		log.info("member = " + member.toString());
	}

}

This is a resource file. Use the key cron.pattern1 to set the execution timing of batch processing It is specified every 0 seconds per minute. Please check the Official API documentation for the format.

application.properties


spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=xxxxxx
spring.datasource.password=xxxxxx
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=true

cron.pattern1: 0 * * * * *

A bean for test data. It is validated using Bean Validation. Among them, I implemented @ExistsInVoicePrat as a custom validation.

Member.java


package jp.co.illmatics.bean;

import javax.validation.constraints.NotEmpty;

import org.springframework.format.annotation.DateTimeFormat;

import jp.co.illmatics.validator.annotation.ExistsInVoicePart;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@AllArgsConstructor
public class Member {

	@NotEmpty(message = "Input first name.")
	private String firstName;

	@NotEmpty(message = "Input family name.")
	private String familyName;

	@ExistsInVoicePart
	private String part;

	@DateTimeFormat(pattern = "yyyy/MM/dd")
	private String birthday;

}

Annotation for custom validation.

ExistsInVoicePart.java


package jp.co.illmatics.validator.annotation;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

import jp.co.illmatics.validator.VoicePartValidator;

@Constraint(validatedBy = {VoicePartValidator.class})
@Target({FIELD})
@Retention(RUNTIME)
public @interface ExistsInVoicePart {

	String message() default "Input voice part.";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    
    @Target({FIELD})
    @Retention(RUNTIME)
    public @interface List {
        ExistsInVoicePart[] value();
    }

}

An Enum for a custom validator.

VoicePart.java


package jp.co.illmatics.enumeration;

public enum VoicePart {

	LEAD_VOCAL("lead vocal"),
	BEATBOXER("beatboxer"),
	BASS("bass"),
	OTHERS("others");

    @SuppressWarnings("unused")
	private final String name;
 
    private VoicePart(String name) {
        this.name = name;
    }
}

Custom validator.

VoicePartValidator.java


package jp.co.illmatics.validator;

import java.util.Arrays;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import jp.co.illmatics.enumeration.VoicePart;
import jp.co.illmatics.validator.annotation.ExistsInVoicePart;

public class VoicePartValidator implements ConstraintValidator<ExistsInVoicePart, String> {

	public void initialize(ExistsInVoicePart annotation) {
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		return Arrays.stream(VoicePart.values()).filter(part -> part.name().equals(value)).findFirst().isPresent();
	}
}

Operation check

Right click on BatchSampleApplication.java, Run as Spring Boot Application.

It runs every 0 seconds every minute. 実行結果.PNG

that's all. Until the end Thank you for reading.

Recommended Posts

I tried Spring Batch
I tried Spring.
I tried Spring State machine
I tried using Spring + Mybatis + DbUnit
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
[Tutorial] Spring Batch
I tried tomcat
I tried youtubeDataApi.
I tried refactoring ①
I tried FizzBuzz.
I tried JHipster 5.1
I tried Lazy Initialization with Spring Boot 2.2.0
I tried Spring Data JDBC 1.0.0.BUILD-SNAPSHOT (-> 1.0.0.RELEASE)
I tried running Autoware
I tried using Gson
I tried QUARKUS immediately
I tried using TestNG
I tried using Galasa
I tried node-jt400 (Programs)
I tried to link JavaFX and Spring Framework.
I tried node-jt400 (execute)
Summary of what I learned in Spring Batch
I tried node-jt400 (Transactions)
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried to get started with Spring Data JPA
Spring Batch job launch parameters
I tried node-jt400 (Environment construction)
I tried DI with Ruby
I tried node-jt400 (IFS write)
I tried node-jt400 (SQL Update)
I tried using azure cloud-init
I tried Drools (Java, InputStream)
I tried Rails beginner [Chapter 1]
I tried the Docker tutorial!
I tried using Apache Wicket
I tried the VueJS tutorial!
I tried node-jt400 (SQL query)
I tried using Java REPL
I tried source code analysis
I tried the FizzBuzz problem
I tried node-jt400 (SQL stream)
I tried node-jt400 (IFS read)
I tried putting XcodeGen + SwiftPM
I tried Rails beginner [Chapter 2]
I tried UPSERT with PostgreSQL.
I tried BIND with Docker
I tried to verify yum-cron
I tried Jets (ruby serverless)
Loop step in Spring Batch
I tried metaprogramming in Java
Spring Boot Introductory Guide I tried [Accessing Data with JPA]
I tried to verify this and that of Spring @ Transactional
[Rails] I tried to implement batch processing with Rake task
I tried to get started with Swagger using Spring Boot
I tried using anakia + Jing now
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
I tried Angular tutorial + SpringBoot + PostgreSQL
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
I tried to chew C # (indexer)