2016-09-23 88 views
1

我一直在與春季啓動了一下,現在,數據源始終在您的application.properties配置在每個例子中,我所看到的,有點像這樣:如何在Spring引導中自動裝入/注入數據源?

# DataSource configuration 
spring.datasource.driver-class-name=org.postgresql.Driver 
spring.datasource.url=jdbc:postgresql://localhost:5432/abcdef 
spring.datasource.username=****** 
spring.datasource.password=****** 

然而,最近我一直在試圖整合春天社會,和我所看到的例子在配置文件中這樣的配置它在Java:

@Bean 
public DataSource dataSource() { 
    DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
    dataSource.setDriverClassName(env.getProperty("db.driver")); 
    dataSource.setUrl(env.getProperty("db.url")); 
    dataSource.setUsername(env.getProperty("db.username")); 
    dataSource.setPassword(env.getProperty("db.password")); 
    return dataSource; 
} 

這使得數據源對象後注射或自動連接到社交配置爲看到here例。

我的問題是,我是否需要像這樣配置一個數據源bean,以便稍後能夠注入數據源,或者將Spring引導句柄給我?

+1

您不需要定義dataSource bean,它將由Spring創建,但您需要在classpath中定義的屬性和驅動程序。 – reos

+0

好酷,基本上我首先列出的配置?謝謝! –

回答

2

不是Spring(或Boot)專家,但Spring Boot會自動提供DataSource類型的Bean,如果屬性存在並且需要它。要使用它,你只需要@Autowire它。

+0

好吧,我可以忽略Intellij告訴我它找不到'Datasource'類型的bean? –

+1

閱讀[文檔](http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html),並對您的應用進行測試運行。 –