반응형

 

1. @EnableScheduling 어노테이션 추가

  • @SpringBootApplication 어노테이션이 있는 Application.java 파일에 @EnableScheduling 어노테이션 추가
@SpringBootApplication
@EnableScheduling
public class Application {

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

}

 

2. Scheduler.java 파일 생성

  • Scheduler 클래스에 @Component 어노테이션 추가

3. 메소드 작성 및 @ Scheduled 어노테이션 작성 (크론표현식 이용)

  • @Scheduled(cron = "0 */5 * * * *") 5분주기
@Component
@Slf4j
public class Scheduler {
	
	@Scheduled(cron = "0 * * * * *")	// 1분마다
	public void test1() throws Exception {
		log.info("1분마다 수행");
	}

	@Scheduled(cron = "0 */5 * * * *")	// 5분마다
	public void test2() throws Exception {
			log.info("5분마다 수행");
	}

	@Scheduled(cron = "0 0 0 * * *")	// 매일 00시 정각
	public void test3() throws Exception {		
		log.info("매일 00시 수행");
	}
	
}
반응형

0. 개발환경

  • Spring Boot 2.6.0
  • Gradle
  • Java11
  • H2 Database
  • IntelliJ

1. build.gradle 의존성 추가

runtimeOnly 'com.h2database:h2'

implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16'

2. src/main/resources/log4jdbc.log4j2.properties 파일 추가

log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
log4jdbc.dump.sql.maxlinelength=0

3. application.properties H2 database 설정 수정

spring.datasource.url=jdbc:log4jdbc:h2:mem:test
spring.datasource.driver-class-name=net.sf.log4jdbc.sql.jdbcapi.DriverSpy

4. src/main/resources/logback.xml 파일 생성

<configuration>
    <!-- Appender, 출력 형식 지정 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>%d{yyyy.MM.dd HH:mm:ss.SSS} {%thread} %-5level %logger{5} - %msg %n</pattern>
            </encoder>
    </appender>
    <logger name="jdbc.resultsettable" level="DEBUG" />
    <logger name="jdbc.sqltiming" level="DEBUG" />
    <logger name="jdbc.resultset" level="OFF" />
    <logger name="jdbc.sqlonly" level="OFF" />
    <logger name="jdbc.audit" level="OFF" />
    <logger name="jdbc.connection" level="OFF" />

    <root level="INFO">
        <appender-ref ref="console"></appender-ref>
    </root>
</configuration>
반응형

SpringBoot에서 jpa를 사용하여 Entity를 생성시에 @Entity 어노테이션을 사용하여 DDL이 자동으로 생성되도록 설정을 하였고

초기 데이터 적재를 위해 resource 디렉토리 아래 data.sql 파일에 insert 문을 넣고 실행시 아래 에러가 발생했다.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/Users/guda/dev/SpringBoot/workspace/demo/out/production/resources/data.sql]: INSERT INTO book (`title`, `author`, `price`) VALUES ('지금 이대로 좋다', '법류 저', 9330); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "BOOK" not found; SQL statement:

처음 공부하는 환경에서 하다 보니 하루동안 삽질 하면서 어떤 문제인지 엄청 삽질을 했다

실행환경 SpringBoot(2.6.4) + Gradle(7.4) + H2(database 2.1.4) + JPA(2.6.4)

결론은 스프링 2.5부터 SQL Script DataSource Initialization이 변경되면서 발생된 문제였다.
schema.sql 및 data.sql 스크립트를 지원하는 데 사용되는 기본 방법이 Spring Boot 2.5에서 재설계되었단다. 

참고한 내용들이 2.5 이전 버전 설정들이여서 정상적으로 작동한 것이다.

해결방안은 application.properties 파일에 아래 설정 값을 추가 하면 된다.

spring.jpa.defer-datasource-initialization=true

 

<참고사항>

Spring Boot 2.5 Release Notes 를 참고해 보면 아래 와 같은 내용이 나온다.
(https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes#hibernate-and-datasql)

기본적으로 data.sql 스크립트는 이제 Hibernate 초기화되기 전에 실행된다.
data.sql 사용하여 Hibernate 의해 생성된 스키마를 채우려면 spring.jpa.defer-datasource-initialization true 설정해라.
데이터베이스 초기화 기술을 혼합하는 것은 권장되지 않지만 이는 data.sql 통해 채우기 전에 하이버네이트에서 생성한 스키마를 기반으로 schema.sql 스크립트를 사용할 수도 있습니다.

Hibernate and data.sql

By default, data.sql scripts are now run before Hibernate is initialized. This aligns the behavior of basic script-based initialization with that of Flyway and Liquibase. If you want to use data.sql to populate a schema created by Hibernate, set spring.jpa.defer-datasource-initialization to true. While mixing database initialization technologies is not recommended, this will also allow you to use a schema.sql script to build upon a Hibernate-created schema before it’s populated via data.sql.

 

+ Recent posts