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

ch93514님의 프로필 이미지

작성한 질문수

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

JPA와 DB 설정, 동작확인

테스트 에러때문에 질문드립니다.

22.06.07 18:44 작성

·

1.2K

1

근 3시간동안 다른 분들 비슷한 에러 메시지의 질문을 확인해봤는데 도저히 해결이 안되어 남깁니다..

에러 메시지는 다음과 같습니다.

java.lang.IllegalStateException: Failed to load ApplicationContext

 

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)

at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)

at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)

at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)

at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)

at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)

at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)

at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)

at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)

at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)

at org.junit.runners.ParentRunner.run(ParentRunner.java:413)

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)

at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)

at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)

at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)

at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)

at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)

at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'memberRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available

at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessProperties(PersistenceAnnotationBeanPostProcessor.java:351)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)

at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)

at

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)

at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)

at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:923)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588)

at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767)

at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)

at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426)

at org.springframework.boot.SpringApplication.run(SpringApplication.java:326)

at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:122)

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)

... 27 more

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available

at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1210)

at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:565)

at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:528)

at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:696)

at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:669)

at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:228)

at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)

at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessProperties(PersistenceAnnotationBeanPostProcessor.java:348)

... 44 more

 

 

그리고

***************************

APPLICATION FAILED TO START

***************************

 

Description:

 

A component required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found.

 

 

Action:

 

Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration.

 이게 상부에 떠있구요

 

 

Member.java

package jpabook.jpashop;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Getter @Setter
public class Member {

@Id
@GeneratedValue
private Long id;
private String username;

}

MemberRepository.java

package jpabook.jpashop;


import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Repository
public class MemberRepository {

@PersistenceContext
private EntityManager em;

public Long save(Member member) {
em.persist(member);
return member.getId();
}

public Member find(Long id) {
return em.find(Member.class, id);
}
}

 

MemberRepositoryTest.java

package jpabook.jpashop;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import static org.junit.jupiter.api.Assertions.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MemberRepositoryTest {

@Autowired
MemberRepository memberRepository;

@Test
@Transactional
public void testMember() throws Exception {
//given
Member member = new Member();
member.setUsername("memberA");

//when
Long savedId = memberRepository.save(member);
Member findMember = memberRepository.find(savedId);

//then
Assertions.assertThat(findMember.getId()).isEqualTo(member.getId());
Assertions.assertThat(findMember.getUsername()).isEqualTo(member.getUsername());

}



 

application.yml

spring: #띄어쓰기 없음
datasource: #띄어쓰기 2
url: jdbc:h2:tcp://localhost/~/jpashop #4
username: sa
password:
driver-class-name: org.h2.Driver
jpa: #띄어쓰기 2
hibernate: #띄어쓰기 4
ddl-auto: create #띄어쓰기 6
properties: #띄어쓰기 4
hibernate: #띄어쓰기 6
# show_sql: true #띄어쓰기 8
format_sql: true #띄어쓰기 8
logging.level: #띄어쓰기 없음
org.hibernate.SQL: debug #띄어쓰기 2

띄어쓰기는 다 수정해봤고, 오타도 봤는데 잘 모르겠습니다..

H2는 켜져있고,

build.gradle은

plugins {
id 'org.springframework.boot' version '2.4.1'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
group = 'jpabook'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-devtools'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
//JUnit4 추가
testImplementation("org.junit.vintage:junit-vintage-engine") {
exclude group: "org.hamcrest", module: "hamcrest-core"
}
}
test {
useJUnitPlatform()
}

위와 같습니다.
도움 주시면 감사하겠습니다.

답변 4

0

ch93514님의 프로필 이미지
ch93514
질문자

2022. 06. 13. 19:28

답변 감사합니다
해결되었습니다.

EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

이 코드가 문제가 되었던 이유는
특정 자동설정 클래스를 비활성화 하는 exclude={DataSourceAutoConfiguration.class} 코드가 

ApplicationContext를 구성하는데 방해했다고 이해하면 될까요?

 

OMG님의 프로필 이미지

2022. 06. 13. 20:37

데이터소스 설정 클래스를 자동설정에서 제외시켜서 발생한 문제로 보시면 됩니다

sy k님의 프로필 이미지

2022. 06. 24. 23:22

OMG님 지나가다가 감사인사 드리고 갑니다 ㅎㅎ 항상 친절하게 답변 달아주셔서 감사드립니다 이게 쉬운일이 아닌데요 ㅠㅠ


0

ch93514님의 프로필 이미지
ch93514
질문자

2022. 06. 09. 22:04

https://drive.google.com/file/d/1DT51d3idJVpSucFhF5Mt2xnuWU95xWfr/view?usp=sharing
링크 남겨드립니다 감사합니다

OMG님의 프로필 이미지

2022. 06. 11. 15:01

프로젝트코드 확인해보았습니다.

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

어노테이션 선언을 제거해주세요.

 

0

ch93514님의 프로필 이미지
ch93514
질문자

2022. 06. 08. 17:34

yml 은 이렇습니다

OMG님의 프로필 이미지

2022. 06. 08. 22:58

yml 상에서는 크게 문제점이 보이진 않는 것 같습니다.

직접 코드를 확인해봐야 할 거 같아요,

전체 프로젝트를 압축해서 구글 드라이브로 공유해서 링크를 남겨주세요.

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

https://bit.ly/3fX6ygx

주의: 업로드시 권한 문제 꼭 확인해주세요

감사합니다

0

OMG님의 프로필 이미지

2022. 06. 07. 20:53

안녕하세요. ch93514님, 공식 서포터즈 OMG입니다.

yml은 띄어쓰기에 유의해야합니다.

url, username과 passowrd,driver-class-name의 띄어쓰기가 다른 것으로 보이네요.

제공해드리는 프로젝트 yml을 복사 붙여넣기 하여 확인해주세요


감사합니다.

 

ch93514님의 프로필 이미지
ch93514
질문자

2022. 06. 08. 01:03

제공해주신 yml을 복사 붙여넣기 해봤지만 같은 에러가 뜹니다..

ch93514님의 프로필 이미지

작성한 질문수

질문하기