programing

구성에서 유형을 정의하는 것을 고려합니다.

starjava 2023. 7. 21. 20:25
반응형

구성에서 유형을 정의하는 것을 고려합니다.

이 튜토리얼(https://www.youtube.com/watch?v=Hu-cyytqfp8 )에 따라 Spring Boot에서 원격 서버의 MongoDB에 연결하려고 합니다.애플리케이션을 실행하면 다음과 같은 메시지가 나타납니다.

설명: com.mongotest.demo에 있는 생성자의 매개 변수 0.시드기에는 'com.mongotest.repository' 유형의 빈이 필요합니다.'학생 리포지토리'를 찾을 수 없습니다.

조치: 'com.mongotest.repository' 유형의 빈을 정의합니다.구성에 '학생 저장소'가 있습니다.

프로젝트 구조입니다.

enter image description here

그리고 여기 제 수업이 있습니다.

    @Document(collection = "Students")
    public class Student {

        @Id
        private String number;
        private String name;
        @Indexed(direction = IndexDirection.ASCENDING)
        private int classNo;

    //Constructor and getters and setters.
    }

    ================================

    @Repository
    public interface StudentRepository extends MongoRepository<Student, String>{

    }

    ================================

    @Component
    @ComponentScan({"com.mongotest.repositories"})
    public class Seeder implements CommandLineRunner{

        private StudentRepository studentRepo;

        public Seeder(StudentRepository studentRepo) {
            super();
            this.studentRepo = studentRepo;
        }

        @Override
        public void run(String... args) throws Exception {
            // TODO Auto-generated method stub

            Student s1 = new Student("1","Tom",1);
            Student s2 = new Student("2","Jerry",1);
            Student s3 = new Student("3","Kat",2);
            studentRepo.deleteAll();
            studentRepo.save(Arrays.asList(s1,s2,s3));

        }

    }

    ================================

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

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>com.mongotest</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>

        <name>demo</name>
        <description>Demo project for Spring Boot</description>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>

        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>

        <dependencies>
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>


    </project>

아래 주석을 추가하십시오.DemoApplication

@SpringBootApplication
@ComponentScan("com.mongotest") //to scan packages mentioned
@EnableMongoRepositories("com.mongotest") //to activate MongoDB repositories
public class DemoApplication { ... }

저의 경우, mysql db를 사용하여 동일한 오류가 발생했습니다.

@EnableJpaResposities를 사용하여 해결됨

@SpringBootApplication
@ComponentScan("com.example.repositories")//to scan repository files
@EntityScan("com.example.entities")
@EnableJpaRepositories("com.example.repositories")
public class EmployeeApplication implements CommandLineRunner{ ..}

주석을 작성하지 않으려면 패키지를 간단히 변경할 수 있습니다.com.mongotest.entities로.com.mongotest.demo.entities그리고.com.mongotest.repositories로.com.mongotest.demo.repositories

Spring Boot 아키텍처는 휴식을 취할 것입니다.실제로 다른 파일과 패키지는 동일한 수준이거나 아래에 있어야 합니다.DemoApplication.java.

저는 세션 서비스 스프링 서비스의 종속성으로 컨스트럭터에 전달해야 했던 RedisManager, JWTokenCreator 및 JWTokenReader 3개의 도우미 클래스가 있습니다.

@SpringBootApplication
@Configuration
public class AuthenticationServiceApplication {
  @Bean
  public SessionService sessionService(RedisManager redisManager, JWTTokenCreator tokenCreator, JWTTokenReader tokenReader) {
    return new SessionService(redisManager,tokenCreator,tokenReader);
  }

  @Bean
  public RedisManager redisManager() {
    return new RedisManager();
  }

  @Bean
  public JWTTokenCreator tokenCreator() {
    return new JWTTokenCreator();
  }

  @Bean
  public JWTTokenReader JWTTokenReader() {
    return new JWTTokenReader();
  }

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

서비스 클래스는 다음과 같습니다.

@Service
@Component
public class SessionService {
  @Autowired
  public SessionService(RedisManager redisManager, JWTTokenCreator 
      tokenCreator, JWTTokenReader tokenReader) {

      this.redisManager = redisManager;
      this.tokenCreator = tokenCreator;
      this.jwtTokenReader = tokenReader;

   }
}

여기서 문제는 정의한 주석에 있습니다.

@구성요소 스캔("com.mongotest")

그러면 프로젝트 구조 'com.mongotest' 아래의 모든 관련 패키지가 스캔되고 모든 하위 패키지 클래스에서 콩이 초기화됩니다.

@Document(collection = "Students")
public class Student {
	
	@Id
	private String number;
	private String name;
	@Indexed(direction = IndexDirection.ASCENDING)
	private int classNo;

//Constructor and getters and setters.
}

================================

@Repository
public interface StudentRepository extends MongoRepository<Student, String>{

}

================================

@Component
@ComponentScan({"com.mongotest.repositories"})
public class Seeder implements CommandLineRunner{

	private StudentRepository studentRepo;
	
	public Seeder(StudentRepository studentRepo) {
		super();
		this.studentRepo = studentRepo;
	}

	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub

		Student s1 = new Student("1","Tom",1);
		Student s2 = new Student("2","Jerry",1);
		Student s3 = new Student("3","Kat",2);
		studentRepo.deleteAll();
		studentRepo.save(Arrays.asList(s1,s2,s3));
		
	}

}

================================

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

언급URL : https://stackoverflow.com/questions/48240271/consider-defining-a-bean-of-type-in-your-configuration

반응형