Spring Boot에서 @Repository 주석이 달린 인터페이스를 자동 연결할 수 없습니다.
스프링 부트 어플리케이션을 개발 중인데 문제가 생겼어요.@Repository 주석 인터페이스를 삽입하려고 하는데 전혀 작동하지 않는 것 같습니다.이 에러가 발생하고 있습니다.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springBootRunner': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pharmacy.persistence.users.dao.UserEntityDao com.pharmacy.config.SpringBootRunner.userEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.pharmacy.config.SpringBootRunner.main(SpringBootRunner.java:25)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pharmacy.persistence.users.dao.UserEntityDao com.pharmacy.config.SpringBootRunner.userEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 16 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pharmacy.persistence.users.dao.UserEntityDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 18 common frames omitted
코드는 다음과 같습니다.
주 응용 프로그램 클래스:
package com.pharmacy.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("org.pharmacy")
public class SpringBootRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootRunner.class, args);
}
}
엔티티 클래스:
package com.pharmacy.persistence.users;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class UserEntity {
@Id
@GeneratedValue
private Long id;
@Column
private String name;
}
저장소 인터페이스:
package com.pharmacy.persistence.users.dao;
import com.pharmacy.persistence.users.UserEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserEntityDao extends CrudRepository<UserEntity,Long>{
}
컨트롤러:
package com.pharmacy.controllers;
import com.pharmacy.persistence.users.UserEntity;
import com.pharmacy.persistence.users.dao.UserEntityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@Autowired
UserEntityDao userEntityDao;
@RequestMapping(value = "/")
public String hello() {
userEntityDao.save(new UserEntity("ac"));
return "Test";
}
}
build.gradle
buildscript {
ext {
springBootVersion = '1.2.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
mainClassName = "com.pharmacy.config.SpringBootRunner"
jar {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-ws")
compile("postgresql:postgresql:9.0-801.jdbc4")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
application.properties:
spring.view.prefix: /
spring.view.suffix: .html
spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=abc123
심지어 코드를 데이터 액세스 jpa와 비교했는데, 이 코드에 무슨 문제가 있는지 생각이 안 나네요.아무쪼록 잘 부탁드립니다.
편집: 위와 같이 코드를 변경했는데 @Repository 인터페이스를 다른 컴포넌트에 삽입할 때 오류가 발생하지 않습니다.그러나 문제가 생겼습니다.컴포넌트를 취득할 수 없습니다(디버깅을 사용).내가 뭘 잘못해서 봄철 부품을 못 찾겠어?
과 다른 경우@SpringBootApplication/@EnableAutoConfiguration의 기본 , " " " "@EnableJpaRepositories를 명시적으로 정의해야 합니다.
「」를 추가해 .@EnableJpaRepositories("com.pharmacy.persistence.users.dao")Spring Boot Runner Spring Boot Runner로 합니다.
저장소를 찾을 수 없는 것과 같은 문제가 발생했습니다.그래서 저는 모든 것을 하나의 패키지로 옮겼습니다.그리고 이것은 내 코드에 아무런 문제가 없다는 것을 의미했다.Repos & Entities를 다른 패키지로 이동하고 Spring Application 클래스에 다음 항목을 추가했습니다.
@EnableJpaRepositories("com...jpa")
@EntityScan("com...jpa")
그 후 서비스(인터페이스 및 구현)를 다른 패키지로 옮기고 Spring Application 클래스에 다음 항목을 추가했습니다.
@ComponentScan("com...service")
이것으로 나의 문제는 해결되었다.
이런 종류의 문제에는 또 다른 원인이 있는데, 제가 이 문제에 대해 한동안 고민하다가 SO에 대한 답을 찾을 수 없었기 때문입니다.
다음과 같은 저장소:
@Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{
}
「」의 UserEntity 를 가지고 있지 않다.@Entity클래스에 주석을 달면 동일한 오류가 발생합니다.
이 오류는 스프링이 저장소를 찾을 수 없지만 엔티티에 문제가 있다는 문제를 해결하는 데 중점을 두기 때문에 이 경우에 혼란을 줍니다.또한 Repository를 테스트하려고 이 답변을 얻었을 경우 이 답변이 도움이 될 수 있습니다.
의 ★★★★★★★★★★★★★★★★★★★★.@ComponentScan이치노
@ComponentScan(basePackages = {"com.pharmacy"})
가 구조의. , 메인 클래스가 바로 에 있습니다.com.pharmacy★★★★★★★★★★★★★★★★★★.
또한 둘 다 필요 없습니다.
@SpringBootApplication
@EnableAutoConfiguration
@SpringBootApplication에는 '주석'이 있습니다.@EnableAutoConfiguration폴트입입니니다
NoSuchBeanDefinitionException스프링 부트(기본적으로 CRUD 저장소 작업 중)에서 다음 주석을 메인 클래스에 넣어야 했습니다.
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages={"<base package name>"})
@EnableJpaRepositories(basePackages="<repository package name>")
@EnableTransactionManagement
@EntityScan(basePackages="<entity package name>")
드, 반, 저, 저, 저, 저, 저, 저, 저, 저, 저, also, also, also, .@Component주석을 실장하고 있습니다.
SpringBoot에서는 기본적으로 JpaRepository가 자동으로 활성화되지 않습니다.명시적으로 추가해야 합니다.
@EnableJpaRepositories("packages")
@EntityScan("packages")
@SpringBootApplication(scanBasePackages=,<youur package name>)
@EnableJpaRepositories(<you jpa repo package>)
@EntityScan(<your entity package>)
Entity class like below
@Entity
@Table(name="USER")
public class User {
@Id
@GeneratedValue
위의 답변으로 넘어가려면 EnableJ에 여러 패키지를 추가할 수 있습니다.PAREpository 태그를 지정하면 저장소 패키지만 지정한 후 "오브젝트가 매핑되지 않음" 오류가 발생하지 않습니다.
@SpringBootApplication
@EnableJpaRepositories(basePackages = {"com.test.model", "com.test.repository"})
public class SpringBootApplication{
}
당신이 가지고 있는 소포와 관련된 것일 수도 있어요.저도 비슷한 문제가 있었습니다.
Description:
Field userRepo in com.App.AppApplication required a bean of type 'repository.UserRepository' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
액션:
하는 것을 해 주세요.repository.UserRepository 입니다
표준화된 명명 규칙을 사용하여 저장소 파일을 패키지에 넣어 해결:
e.g. com.app.Todo (for main domain files)
그리고.
com.app.Todo.repository (for repository files)
이렇게 하면 봄철은 저장소가 어디에 있는지 알 수 있습니다.그렇지 않으면 순식간에 혼란이 생깁니다.:)
이게 도움이 됐으면 좋겠다.
잘못된 패키지를 스캔하고 있습니다.
@ComponentScan("**org**.pharmacy")
필요한 장소:
@ComponentScan("**com**.pharmacy")
패키지 이름은 org가 아니라 com으로 시작하므로
나도 이 주제에 문제가 좀 있었어.다음 예시와 같이 Spring boot runner 클래스에서 패키지를 정의해야 합니다.
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"controller", "service"})
@EntityScan("entity")
@EnableJpaRepositories("repository")
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
도움이 됐으면 좋겠네요!
여기 오류가 있습니다.누군가 말했듯이 당신은 com의 org.parmacy를 사용하고 있습니다.컴포넌트 내의 약국
package **com**.pharmacy.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("**org**.pharmacy")
public class SpringBootRunner {
이 @DataJpaTest그 해답은 다음과 같습니다.
되지 않음@Repository@DataJpaTest다음의 2개의 수정 중 하나를 실시해 주세요.
첫번째
@SpringBootTest". 합니다.그러나 이렇게 하면 애플리케이션 컨텍스트 전체가 부팅됩니다.
두 번째 (더 나은 솔루션)
다음과 같이 필요한 특정 저장소를 Import합니다.
@DataJpaTest
@Import(MyRepository.class)
public class MyRepositoryTest {
@Autowired
private MyRepository myRepository;
Data Data MongoDB에 .패키지 경로를 추가해야 했습니다.@EnableMongoRepositories
의존관계를 변경하여 이 문제를 해결했습니다.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
그거랑 같이:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
이렇게 하면 다음과 같은 양극화를 사용할 필요가 없습니다.
@EnableAutoConfiguration
@ComponentScan({"controller", "service"})
@EntityScan("entity")
@EnableJpaRepositories("repository")
)
비슷한 문제가 있었지만 다른 원인이 있었습니다.
내 경우, 저장소를 정의하는 인터페이스에서 문제가 발생했습니다.
public interface ItemRepository extends Repository {..}
템플릿의 종류를 생략하고 있었습니다.올바른 설정:
public interface ItemRepository extends Repository<Item,Long> {..}
성공했어.
인@ComponentScan("org.pharmacy")패키지를 선언합니다.하지만 컴포넌트는 패키지에 포함되어 있습니다.
다음 사항을 확인합니다.@Service또는@Component저장소의 자동 배선을 시도하고 있습니다.SpringApplication.class. 서브폴더에 있는지 확인합니다.service/.
Maven 구성에 Lombok 주석 프로세서의 종속성을 추가하는 것을 잊어버렸을 때 같은 문제가 발생할 수 있습니다.
pom.xml에 대한 아래의 의존관계를 추가하면 문제가 해결되었습니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
메인 클래스가 com.example 패키지에 있는 경우 다른 패키지에 있는 다른 클래스를 com.example 패키지로 호출해야 합니다(예: Controller package com.example.controller).
그리고.
메인 클래스 패키지를 com.example.main으로 지정한 경우 메인 클래스는 com.example.main이 아닌 com.example.main에 있어야 합니다.다른 클래스는 com.package.main.controller와 같은 패키지 내에 있어야 합니다.
이 답변의 대부분은 솔루션 전체의 일부이기 때문에 많은 도움이 됩니다.나에게 그것은 그들 중 일부의 혼합이었다.
당신의.ComponentScan패키지가 잘못되었습니다.변경 내용:
@ComponentScan("com.pharmacy")
다음 항목도 추가해야 합니다.
@EnableJpaRepositories
고객님께SpringBootApplication클래스, 여기:SpringBootRunner.
Maven 의존관계를 변경해야 했습니다(Gradle도 마찬가지).
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
수신인:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
의존관계를 갱신하는 것을 잊지 마세요.
그리고 나서 나는 또한 수입품들을 바꿔야 했다.Entity클래스 대상:
import jakarta.persistence.*;
언급URL : https://stackoverflow.com/questions/29221645/cant-autowire-repository-annotated-interface-in-spring-boot
'programing' 카테고리의 다른 글
| React에서 Formik과 함께 사용자 지정 입력을 사용하는 방법 (0) | 2023.04.05 |
|---|---|
| 매개 변수가 있는 함수를 reactj의 소품을 통해 전달 (0) | 2023.04.05 |
| Angularjs 오류 알 수 없는 공급자 (0) | 2023.04.05 |
| 다른 프로젝트에서 Spring Boot Jar에 종속성을 추가하려면 어떻게 해야 합니까? (0) | 2023.04.05 |
| Typescript에 있는 객체의 키와 값의 유형 (0) | 2023.04.05 |