2015-10-12 9 views
5

私は関連の設定がapplication.propertiesに設定されている場合に春ブーツは、自動的にのようなdataSource Beanを作成します知っている:、@Autowired DataSourceはコメントアウトされている場合はなぜSpringSourceアプリケーションでDataSourceを自動起動できないのですか?

package com.synline.mdataserver; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.CommandLineRunner; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.annotation.AnnotationConfigApplicationContext; 
import org.apache.tomcat.jdbc.pool.DataSource; 

@SpringBootApplication 
public class Application implements CommandLineRunner { 

    @Autowired 
    AnnotationConfigApplicationContext context; 

    /*@Autowired 
    DataSource dataSource;*/ 

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

    @Override 
    public void run(String... args) throws Exception { 
     DataSource dataSource = (DataSource)context.getBean("dataSource"); 
     System.out.println(dataSource); 

     while (true) { 
      Thread.sleep(5000); 
     } 

    } 
} 

spring.datasource.url = jdbc:mysql://192.168.10.103:3306/hms?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull 
spring.datasource.username=root 
[email protected] 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver 

アプリケーションコードをBeanの情報が表示されます:

[email protected]{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....} 

私はSpring Boot Reall豆を作りました。 @Autowried DataSourceが使用されている場合

はしかし、例外はない、そのインタフェースの特定の実装としては、そのような豆

Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.tomcat.jdbc.pool.DataSource com.synline.mdataserver.Application.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.apache.tomcat.jdbc.pool.DataSource] 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)} 
+0

スニペットだけでなく、うまくいかないケースも投稿してください。また、特定のtomcat型ではなく、 'javax.sql.DataSource'を使用する必要があります。 –

+0

ありがとうございます。投稿を再編集し、完全なコードを追加します。 –

+0

ああ、Deinum、あなたはポイントを取得します。私が "import org.apache.tomcat.jdbc.pool.DataSource;"の代わりに "javax.sql.DataSourceをインポート"したら、もう問題はありません! –

答えて

4

あなたの変数は、標準のJDBCデータソース(すなわちjavax.sql.DataSource)として宣言すべきではない文句を発生します。

+0

はい、これが根本原因です。ありがとう! –

関連する問題