programing

Spring Boot-클래스 경로 리소스에 정의 된 이름이 'dataSource'인 빈 생성 오류

nasanasas 2021. 1. 10. 17:24
반응형

Spring Boot-클래스 경로 리소스에 정의 된 이름이 '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이 Spring에 의해 초기화 될 수없는 것 같습니다 ....

    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

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의 수명주기를 실행할 때 발생합니다 test. IntelliJ에서 degub 모드로 실행하면 오류가 출력되지 않습니다.

업데이트 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

내 응용 프로그램 속성을 변경했습니다. 그리고 모든 조합을 시도했지만 작동하지 않습니다. ; (

Maven 출력 :

-------------------------------------------------------
 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.

초기 문제는 자동 구성에있는 것 같습니다.

데이터 소스가 필요하지 않은 경우 자동 구성 프로세스에서 제거하면됩니다.

@EnableAutoConfiguration(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>

The hibernate.* properties are useless, they should be spring.jpa.* properties. Not to mention that you are trying to override those already set by using the spring.jpa.* properties. (For the explanation of each property I strongly suggest a read of the Spring Boot reference guide.

spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true

# Hibernate
spring.jpa.hibernate.ddl-auto=update

Also the packages to scan are automatically detected based on the base package of your Application class. If you want to specify something else use the @EntityScan annotation. Also specifying the most toplevel package isn't really wise as it will scan the whole class path which will severely impact performance.


change below line of code

spring.datasource.driverClassName

to

spring.datasource.driver-class-name

This problem comes while you are running Test. Add dependency

testCompile group: 'com.h2database', name: 'h2', version: '1.4.197' 

Add folder resources under test source add file bootstrap.yml and provide content.

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

this will setup your data source.


If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****


Check that you have database dependency at runtime group at build.gradle

runtime group: 'com.h2database', name: 'h2', version: '1.4.194'

or change scope from test to runtime if you use Maven

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.194</version>
    <scope>runtime</scope>
</dependency>

In my case this was happening because org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource is an autowired field without a Qualifier and I am using multiple datasources with qualified names. I solved this problem by using @Primary arbitrarily on one of my dataSource bean configurations like so

@Primary
@Bean(name="oneOfManyDataSources")
public DataSource dataSource() { ... }

I suppose they want you to implement AbstractRoutingDataSource, and then that auto configuration will just work because no qualifier is needed, you just have a single data source that allows your beans to resolve to the appropriate DataSource as needed. Then you don't need the @Primary or @Qualifier annotations at all, because you just have a single DataSource.

In any case, my solution worked because my beans specify DataSource by qualifier, and the JPA auto config stuff is happy because it has a single primary DataSource. I am by no means recommending this as the "right" way to do things, but in my case it solved the problem quickly and did not deter the behavior of my application in any noticeable manner. Will hopefully one day get around to implementing the AbstractRoutingDataSource and refactoring all the beans that need a specific DataSource and then perhaps that will be a neater solution.


I was facing this issue even after supplying all required datasource properties in application.properties. Then I realized that properties configuration class was not getting scanned by Spring boot because it was in different package hierarchy compared to my Spring boot Application.java and hence no properties were applied to datasource object. I changed the package name of my properties configuration class and it started working.


Not directly related to the original question but this will be useful for someone. This error occurred to me with a simple two project structure. One project was handling some database operations with spring jdbc (say A) and the other did not have any jdbc operations at all(say B). But still this error appeared while I was starting service B. Saying the datasource should be initialized properly.

As I figured out I had added this dependency to the parent pom of the two modules

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

This caused spring to initialize the jdbc dependencies for the project B too. So, I moved it to poject A's pom, everything was fine.

Hope this would help someone


Are you running the application as a jar? ( java -jar xxxx.jar)

If so, do you have the application.properties stored in that jar ?

If no, try to figure out why :

  • To be automatically package in the jar, the files can be in : src/main/resources/application.properties
  • The maven plugin in the pom.xml can also be configured

It worked for me you can try your: Add this to VM options in Tomcat

-DdevBaseDir="C:\Your_Project_Dir_Path"

In my case I just ignored the following in application.properties file:

# Hibernate

#spring.jpa.hibernate.ddl-auto=update

It works for me....


Give you something different, when you encounter this kind of error, cannot create bean datasource in a test case.

It might be caused by some reasons:

  1. No datasource, you will need to create your datasource, h2 in-memory datasource or whatever, or you can choose the way like exclude={datasource··}.
  2. You have your datasource, like MySQL, but it still not work. It was caused by class AutoConfigureTestDatabase, It will choose a datasource for you which may cause ambiguity.

Solution: add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) to avoid replace the default datasource.


I was facing the same problem for several days, and finally the issue isn't with the code, the problem commes from maven, you must delete all the files that he downloaded from your hard drive "C:\Users\username.m2\repository", and do another update maven for your project, that will fix your problem.


I solved my problem with the change of the parent Spring Boot Dependency.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>

to

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
</parent>

For more Information, take a look at the release notes: Spring Boot 2.1.0 Release Notes

ReferenceURL : https://stackoverflow.com/questions/28042426/spring-boot-error-creating-bean-with-name-datasource-defined-in-class-path-r

반응형