스프링 부트 - 클래스 경로 리소스에 정의된 'dataSource' 이름의 콩을 만드는 동안 오류가 발생했습니다.
Spring Boot 웹 어플리케이션을 사용하고 있습니다.RESTful 어프로치를 중심으로 하고 있습니다.모든 설정은 정상적으로 이루어지고 있습니다만, 어떠한 이유로 MainController가 요구를 처리할 수 없습니다.404 에러가 발생합니다.어떻게 고치죠?
@Controller
public class MainController {
@Autowired
ParserService parserService;
@RequestMapping(value="/", method= RequestMethod.GET)
public @ResponseBody String displayStartPage(){
return "{hello}";
}
}
어플
@Configuration
@ComponentScan(basePackages = "")
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
파서 컨트롤러
@RestController
public class ParserController {
@Autowired
private ParserService parserService;
@Autowired
private RecordDao recordDao;
private static final Logger LOG = Logger.getLogger(ParserController.class);
@RequestMapping(value="/upload", method= RequestMethod.POST)
public @ResponseBody String fileUploadPage(
}
}
갱신하다
봄까지 MySQL을 초기화할 수 없는 것 같습니다.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed;
nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
업데이트 2
application.properties
# Database
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/logparser
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: /
업데이트 4
하지 않는 것 같습니다.@RequestMapping
설정되었습니다.왜왜??
Maven의 사이클 PS를 할 때 합니다. 메이븐의 라이프 사이클을 실행하면
test
IntelliJ에서 디거브 모드로 실행해도 에러는 출력되지 않습니다.
갱신 5
또, 튜토리얼의 설명대로 이 DAO를 사용하고 있습니다.
public interface RecordDao extends CrudRepository<Record, Long> {
}
http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/
업데이트 6
응용 프로그램 속성을 변경했습니다.그리고 모든 조합을 시도했지만 효과가 없었다.;(
메이븐 출력:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running IntegrationTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.365 sec <<< FAILURE! - in IntegrationTest
saveParsedRecordsToDatabase(IntegrationTest) Time elapsed: 2.01 sec <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
첫 번째 문제는 auto-config에 있는 것 같습니다.
데이터 소스가 필요하지 않은 경우 자동 구성 프로세스에서 데이터 소스를 삭제하기만 하면 됩니다.
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
편집: 메인 클래스에서 @Spring Boot Application을 사용하는 경우:
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
Spring Boot에 데이터 소스를 구성하기에 충분한 데이터가 전달되지 않은 것으로 판단됩니다.
기존 작성/입력application.properties
과 같이 덧붙이다
spring.datasource.driverClassName=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
각 속성에 값을 추가해야 합니다.
MySQL JDBC 드라이버를 잊어버렸을 수 있습니다.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
같은 에러가 발생하고 있었는데, 그것이 Spring JPA, Hibernate, Mysql 또는 Jackson과 같은 pom.xml의 의존관계가 누락되었기 때문이라는 것을 알게 되었습니다.따라서 pom.xml에 의존관계가 누락되지 않았는지 확인하고 버전 호환성을 확인하십시오.
<!-- Jpa and hibernate -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.3.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
저는 스프링 부츠 2.6.0으로 작업하고 있습니다.여러 가지 답변을 시도했지만 충분하지 않았습니다.내가 찾은 한 가지 일시적인 해결책은
@SpringBootApplication(exclude = SqlInitializationAutoConfiguration.class)
서버가 실행되고 h2-console이 표시되지만 data.sql 파일에 연결할 수 없습니다.이것이 내가 받은 오류이다.
Database "mem:testdb" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149
이것이 제가 찾은 해결책입니다(일부 솔루션은 이미 사용되고 있습니다).이러한 행을 application.properties 파일에 추가합니다.
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.defer-datasource-initialization=true
서버를 재실행한 후 h2 콘솔에서 브라우저의 DB에 다시 접속합니다.
기본적으로는 데이터입니다.이제 hibernate가 초기화되기 전에 sql 스크립트가 실행됩니다.이를 통해 기본 스크립트 기반 초기화 동작이 Flyway 및 Liquibase와 일치합니다.데이터를 사용하고 싶다면.sql을 사용하여 휴지 상태로 작성된 스키마를 채우려면 spring.jpa.defer-datasource-initialization을 true로 설정합니다.
spring.jpa.displays-initialization=true로 문제를 해결합니다.
이 문제는 테스트 실행 중에 발생합니다.종속성 추가
testCompile group: 'com.h2database', name: 'h2', version: '1.4.197'
테스트 소스 아래에 bootstrap.yml 파일을 추가하고 콘텐츠를 제공합니다.
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:TEST
driver-class-name: org.h2.Driver
username: username
password: password
hikari:
idle-timeout: 10000
데이터 소스를 설정합니다.
hibernate.*
가 없다가 없다.spring.jpa.*
또, 이미 되어 있는 있는 은 말할 것도 ,spring.jpa.*
(각 속성에 대한 설명은 Spring Boot 참조 가이드를 읽는 것이 좋습니다.
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true
# Hibernate
spring.jpa.hibernate.ddl-auto=update
, 스캔 는, 「 」, 「 」, 「 」의 베이스 패키지에 됩니다.Application
class. 하십시오. 른른른른@EntityScan
하는 것은 에 심각한 을 미치기 하지 않습니다.또한 최상위 패키지를 지정하는 것은 성능에 심각한 영향을 미치는 전체 클래스 경로를 검색하기 때문에 그다지 현명하지 않습니다.
코드 라인 이하로 변경하다
spring.datasource.driverClassName
로.
spring.datasource.driver-class-name
application.properties ation 、 application . properties 、 application . properties 。
springsql..mysql.url:jdbc:mysql://?cloodSqloodInstance=&sqlocketCom.com.com.com.com.com.com..com.com.com.com.sql
build.gradle 런타임 그룹에 데이터베이스 종속성이 있는지 확인합니다.
runtime group: 'com.h2database', name: 'h2', version: '1.4.194'
또는 Maven을 사용하는 경우 테스트에서 런타임으로 범위를 변경합니다.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.194</version>
<scope>runtime</scope>
</dependency>
원래 질문과는 직접 관련이 없지만 누군가에게 도움이 될 것입니다.이 에러는 단순한 2개의 프로젝트 구조에서 발생했습니다.한 프로젝트는 스프링 JDBC(A라고 함)를 사용하여 데이터베이스 작업을 처리하고 있었고, 다른 프로젝트는 JDBC 작업을 전혀 수행하지 않았습니다(B라고 함).그래도 서비스 B를 시작할 때 이 에러가 발생했습니다.데이터 소스를 올바르게 초기화해야 한다고 말합니다.
이 의존성을 두 모듈의 부모 폼에 추가한 것을 알게 되었습니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
이로 인해 스프링은 프로젝트 B의 JDBC 의존관계도 초기화했습니다.그래서 프로젝트 A의 폼으로 옮겼는데 아무 문제 없었어요
이것이 누군가에게 도움이 되기를 바란다.
제 경우 org.springframework.boot.autoconfigure.orm.jpa가 원인입니다.JpaBaseConfiguration.dataSource는 수식자가 없는 자동 입력 필드이며 수식자 이름의 여러 데이터 소스를 사용하고 있습니다.이 문제는 데이터 중 하나에서 @Primary를 임의로 사용하여 해결했습니다.Source bean은 다음과 같습니다.
@Primary
@Bean(name="oneOfManyDataSources")
public DataSource dataSource() { ... }
AbstractRoutingDataSource를 구현해 달라고 하면 수식자가 필요 없기 때문에 자동 설정이 기능합니다.필요에 따라 적절한 DataSource로 해결할 수 있는 단일 데이터 소스만 있으면 됩니다.그러면 단일 DataSource가 있기 때문에 @Primary 또는 @Qualifier 주석이 전혀 필요하지 않습니다.
어쨌든, 수식자 마다 DataSource 가 지정되어 있기 때문에, JPA auto config 에는 프라이머리 DataSource 가 1개 포함되어 있기 때문에, 솔루션이 유효했습니다.저는 이것을 올바른 방법으로 추천하는 것은 결코 아니지만, 저 같은 경우에는 문제를 빠르게 해결했고 제 어플리케이션의 동작을 눈에 띄게 억제하지 못했습니다.언젠가는 Abstract Routing Data Source를 구현하여 특정 Data Source를 필요로 하는 모든 콩을 리팩터링할 수 있기를 바랍니다.그것이 아마도 더 새로운 솔루션이 될 것입니다.
application.properties에서 필요한 데이터 소스 속성을 모두 제공했는데도 이 문제에 직면해 있었습니다.그 후 속성 컨피규레이션클래스가 Spring boot Application.java와 다른 패키지 계층에 있기 때문에 데이터 소스 오브젝트에 속성이 적용되지 않았기 때문에 Spring boot에 의해 스캔되지 않는다는 것을 알게 되었습니다.속성 구성 클래스의 패키지 이름을 변경했는데 작동하기 시작했습니다.
제 경우 application.properties 파일에서 다음 사항을 무시했습니다.
휴지 상태
# spring.jpa.containate.ddl-auto=업데이트
나한텐 효과가 있어요.
기본적으로는 Spring Boot의 최신 버전에서는 데이터가 로드됩니다.sql은 테이블이 생성되기 전에 수행됩니다.spring.jpa.spring-initialization=true를 사용합니다.
예 -
**In application.properties :- **
spring.jpa.show-sql=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.h2.console.enabled=true
spring.jpa.defer-datasource-initialization=true
고마워 아타르 카림
애플리케이션을 병처럼 실행하고 있습니까?( java - jar xxxx.jar)
그렇다면 application.properties가 그 항아리에 저장되어 있습니까?
[아니오]의 경우는, 그 이유를 확인합니다.
- jar에 자동으로 패키지화하려면 파일은 src/main/resources/application.properties에 있습니다.
- pom.xml의 maven 플러그인도 설정할 수 있습니다.
다음 기능을 사용해 보십시오.Tomcat의 VM 옵션에 추가
-DdevBaseDir="C:\Your_Project_Dir_Path"
이와 다른 점이 있습니다.이러한 에러가 발생했을 경우,는 테스트 케이스에 bean 데이터 소스를 작성할 수 없습니다.
다음과 같은 이유로 인해 발생할 수 있습니다.
- 데이터 소스는 필요 없습니다.데이터 소스, h2 인메모리 데이터 소스, 또는 그 외의 것을 작성할 필요가 있습니다.또는, 다음과 같은 방법을 선택할 수 있습니다.
exclude={datasource··}
. - MySQL과 같은 데이터 소스가 있지만 여전히 작동하지 않습니다.그것은 수업 때문에 일어났다.
AutoConfigureTestDatabase
불명확한 원인이 될 수 있는 데이터 소스를 선택합니다.
솔루션: 추가@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
기본 데이터 소스를 교체하지 않도록 합니다.
며칠 동안 같은 문제에 직면했지만, 결국 문제는 코드에 있는 것이 아니라 메이븐에서 발생한 문제이므로 하드 드라이브에서 다운로드한 모든 파일을 삭제해야 합니다. "C:\Users\username.m2\repository"를 클릭하여 프로젝트를 다시 업데이트하고 문제를 해결합니다.
부모의 스프링 부트 의존 관계를 변경하여 문제를 해결했습니다.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
로.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
자세한 내용은 Spring Boot 2.1.0 릴리즈 노트를 참조하십시오.
MySQL에서 데이터베이스 생성
create database springboot2;
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/springboot2
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port=9192
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
메인 클래스
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
모델 클래스
package com.First.Try.springboot.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="PRODUCT_TBL1")
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private int quantity;
private double price;
....
....
....
}
pom 파일에서 h2 설정을 사용한 적이 없습니다.추가해서 이 문제는 해결되었습니다.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
데이터 소스에 문제가 있는 것 같습니다.데이터 소스가 필요 없는 경우 다음 명령을 사용하여 데이터 소스를 비활성화하면 됩니다.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
이것을 application.properties에 넣기만 하면 됩니다.
mysql을 사용하는 경우 2개의 종속성이 필요합니다.
1
. <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
portgress를 사용하는 경우 필요한 것은 다음과 같습니다.
1.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
h2를 사용하여 데이터를 추가해야 합니다.sql 꼭 추가해 주세요.
spring.jpa.defer-datasource-initialization=true
application.properties로 설정합니다.
다음은 application.properties 파일입니다.
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
DB 브라우저 플러그인과 함께 IntelliJ 커뮤니티 에디션을 사용하고 있습니다.
나한텐 효과가 있어...
이 문제를 해결하려면 기본 키 열 값 @NotNull을 NULL 주석이 아닌 주석으로 지정하면 작동합니다.
언급URL : https://stackoverflow.com/questions/28042426/spring-boot-error-creating-bean-with-name-datasource-defined-in-class-path-r
'programing' 카테고리의 다른 글
디렉토리에서 모든 PHP 파일을 포함()하려면 어떻게 해야 합니까? (0) | 2023.01.01 |
---|---|
Ajax를 사용하여 PDF 파일 다운로드 및 열기 (0) | 2023.01.01 |
자바어로 뮤텍스와 세마포어가 뭐죠?주된 차이점은 무엇입니까? (0) | 2023.01.01 |
JavaScript에서 스택과 큐를 구현하려면 어떻게 해야 합니까? (0) | 2023.01.01 |
SQL Chemy IN 조항 (0) | 2023.01.01 |