인프런 커뮤니티 질문&답변

이도현님의 프로필 이미지

작성한 질문수

실전! Querydsl

조회 API 컨트롤러 개발

스프링 부트 2.4 이후 profile yml 설정 질문입니다.

24.06.22 23:17 작성

·

189

·

수정됨

0

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.

1. 강의 내용과 관련된 질문을 남겨주세요.
2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.
(자주 하는 질문 링크: https://bit.ly/3fX6ygx)
3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.
(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)

질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.
=========================================
[질문 템플릿]
1. 강의 내용과 관련된 질문인가요? (예/아니오)
2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)
3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)

[질문 내용]
여기에 질문 내용을 남겨주세요.

 

여태 영한님 수업을 들으면서나, 혼자서 뭔가 해보면서 오류가 나도 어떻게든 이 방법 저 방법 붙잡고 해보면 해결이 됐었는데, 스프링 공식 문서를 보고 따라해도 안되고, 구글링을 해도 안 돼서 도저히 못 하겠어서 여쭙게 되었습니다. 먼저 저의 Gradle 컴파일 시 세팅과 샘플 데이터 코드 부터 보여드리겠습니다.

package study.querydsl.controller;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import study.querydsl.entity.Member;
import study.querydsl.entity.Team;

@Profile("local")
@Component
@RequiredArgsConstructor
public class InitMember {

    private final InitMemberService initMemberService;

    @PostConstruct
    public void init() {
        initMemberService.init();
    }

    static class InitMemberService {
        @PersistenceContext
        private EntityManager em;

        @Transactional
        public void init() {
            Team teamA = new Team("teamA");
            Team teamB = new Team("teamB");
            em.persist(teamA);
            em.persist(teamB);

            for (int i = 0; i < 100; i++) {
                Team selectedTeam = i % 2 == 0 ? teamA : teamB;
                em.persist(new Member("member" + i, i, selectedTeam));
            }
        }
    }

}

이 부분은 제가 봤을땐 문제 없는 것 같습니다. 이제 제가 yml 파일에서 시도해봤던 방법들을 보여드리겠습니다.


spring:
  profiles:
    active: local
---
spring:
  config:
    activate:
      on-profile: local
---
spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/querydsl
    username: sa
    password:
    driver-class-name: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
#        show_sql: true # show_sql : `System.out` 에 하이버네이트 실행 SQL을 남긴다
        format_sql: true
        use_sql_comments: true # 실행되는 JPQL을 볼 수 있다.

logging.level:
  org.hibernate.SQL: debug # org.hibernate.SQL : logger를 통해 하이버네이트 실행 SQL을 남긴다.
#  org.hibernate.type: trace # SQL  실행 파라미터를 로그로 남긴다.

첫 번째로 시도했던 방법입니다. application.yml입니다. 아래에 오류 첨부 하겠습니다.

 

Execution failed for task ':QuerydslApplication.main()'.

> Process 'command '/Users/idohyeon/Library/Java/JavaVirtualMachines/corretto-17.0.11/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:

> Run with --stacktrace option to get the stack trace.

> Run with --info or --debug option to get more log output.

> Run with --scan to get full insights.

> Get more help at https://help.gradle.org.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

For more on this, please refer to https://docs.gradle.org/8.8/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.

BUILD FAILED in 2s

3 actionable tasks: 2 executed, 1 up-to-date

 

첫 번째 방법 시도시 오류 입니다.


두 번째 방법 입니다.

#spring:
#  profiles:
#    active: local
#---
spring:
  config:
    activate:
      on-profile: local
---
spring:
  datasource:
    url: jdbc:h2:tcp://localhost/~/querydsl
    username: sa
    password:
    driver-class-name: org.h2.Driver

  jpa:
    hibernate:
      ddl-auto: create
    properties:
      hibernate:
#        show_sql: true # show_sql : `System.out` 에 하이버네이트 실행 SQL을 남긴다
        format_sql: true
        use_sql_comments: true # 실행되는 JPQL을 볼 수 있다.

logging.level:
  org.hibernate.SQL: debug # org.hibernate.SQL : logger를 통해 하이버네이트 실행 SQL을 남긴다.
#  org.hibernate.type: trace # SQL  실행 파라미터를 로그로 남긴다.

application.yml입니다. 알아보니 스프링 부트 2.4부터는 spring.profiles로 설정하면 안되고

spring.config.activate.on-profile로 설정해야 된다고 해서 맨 위 spring.profiles.active 이 부분 빼고 해보았습니다.

그래도 되지 않습니다. 하지만 그래도 이때는 정상적으로 실행이 되긴 하지만 profile이 먹히지 않아 샘플 데이터들이 insert 나가지도 않고,

디비에도 들어와 있지 않습니다.


세 번째 방법 입니다.

 

spring:
  config.activate.on-profile: local

application-local.yml 파일을 위와 같이 만들어둔 상태에서 첫 번째 방법, 두 번째 방법을 시도해봤는데 둘 다 첫 번째 방법 때와 같은 오류가 발생합니다.


https://docs.spring.io/spring-boot/reference/features/profiles.html#page-title

마지막으로 이번엔 공식 문서를 보고 따라해봤던 방법입니다. 이 방법까지 해봤는데도 해결이 되지 않습니다.

 

답변 2

0

김영한님의 프로필 이미지
김영한
지식공유자

2024. 06. 25. 20:19

안녕하세요. 이도현님

이럴 때는 발생한 오류 메시지를 잘 확인하는 것이 먼저입니다 🙂

Parameter 0 of constructor in study.querydsl.controller.InitMember required a bean of type 'study.querydsl.controller.InitMember$InitMemberService' that could not be found.

이 메시지를 보면 InitMember에 있는 중첩 클래스인 InitMemberService를 찾을 수 없다고 하는데요.

 

다음 코드를 보면 중첩 클래스가 스프링 빈으로 등록되어 있지 않습니다.

@Profile("local")
@Component
@RequiredArgsConstructor
public class InitMember {

    private final InitMemberService initMemberService;

    @PostConstruct
    public void init() {
        initMemberService.init();
    }

    static class InitMemberService {
        @PersistenceContext
        private EntityManager em;
    }
    ...
}

 

다음과 같이 중첩 클래스에도 @Component를 추가해주시면 됩니다 🙂

    @Component // 추가
    static class InitMemberService {
        @PersistenceContext
        private EntityManager em;
    }

감사합니다.

이도현님의 프로필 이미지
이도현
질문자

2024. 06. 27. 17:32

아이고 분명 오류 다 봤다 생각했었는데 놓친게 있었네요 감사합니다

0

David님의 프로필 이미지

2024. 06. 24. 15:28

안녕하세요. 이도현님, 공식 서포터즈 David입니다.

도움을 드리고 싶지만 질문 내용만으로는 답변을 드리기 어렵습니다.

실제 동작하는 전체 프로젝트를 ZIP파일로 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.

구글 드라이브 업로드 방법은 다음을 참고해주세요.

https://bit.ly/3fX6ygx

주의: 업로드시 링크에 있는 권한 문제 꼭 확인해주세요

추가로 다음 내용도 코멘트 부탁드립니다.

1. 문제 영역을 실행할 수 있는 방법

2. 문제가 어떻게 나타나는지에 대한 상세한 설명


링크: 공식 서포터즈

링크: 자주하는 질문

감사합니다.

이도현님의 프로필 이미지
이도현
질문자

2024. 06. 24. 16:23

https://drive.google.com/file/d/1Xuf-F2wAn-V_dD6VxcwUf-oy_-rrmONE/view?usp=share_link

 

  1. src/main/java/study/querydsl/QuerydslApplication.java 를 실행하면 됩니다.

  2. src/main/java/study/querydsl/controller/InitMember.java 파일에서

    @Profile() 어노테이션을 이용해서 main에서 실행할 때의 환경과 test 환경에서 실행할 때의 데이터들을 따로 설정하려는 상황인데, main에서 실행할 때 h2 database에 샘플 데이터를 넣는 과정에서 resources/application.yml 파일에서 profile 설정하는 것이 제대로 되지 않아 샘플 데이터가 DB로 들어가지 않는 것 같습니다. 현재 스프링 부트 버전은 3.3.0 사용하고 있습니다.