2017-02-25 94 views
0

當我們使用spring jdbc時,首先定義一個dataSource bean並在創建jdbcTemplate對象時注入它。我想知道的是,我們是否需要在原型範圍內定義這個數據源。除非整個應用程序只有一個dataSource對象。我認爲這會影響應用程序的性能。數據源是否需要在spring的原型範圍內jdbc

這裏是我如何在spring配置文件中定義dataSouce。

<bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource" > 
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
<property name="url" value="jdbc:mysql://localhost:3306/testdb" /> 
<property name="username" value="root" /> 
<property name="password" value="123" /> 
</bean> 

在我的DAO類中,我有如下所示的自動裝配的dataSOurce。

@Repository 
public class RecordDAOImpl { 

JdbcTemplate jdbcTemplate = null; 

@Autowired 
public void setDataSource(DataSource dataSource) { 
    this.jdbcTemplate = new JdbcTemplate(dataSource); 
} 

} 

讓我知道什麼是爲spring mvc web應用程序定義dataSource的最佳方法。

回答

1

我想知道什麼是我們需要在原型範圍

來定義這個數據源不,我們不需要。我想這不是個好主意,我們可以使用某種連接池數據源和單例作用域bean。

我們也可以有多個數據庫,並提供每個自己的數據源單身作用域,這是沒有任何問題的。

讓我知道什麼是爲spring mvc web應用程序定義dataSource的最佳方法。

在xml文件中定義數據源沒有任何問題(儘管許多開發人員似乎都避免使用xml)。我喜歡用java配置來做,因爲我覺得它更易於閱讀。

取決於驅動程序和數據庫它看起來或多或少這樣的:

@Configuration 
class DatasourceConfig { 

    @Bean 
    DataSource datasource() { 
     PGPoolingDataSource dataSource = new PGPoolingDataSource(); 
     dataSource.setPassword("pass"); 
     dataSource.setPortNumber(123); 
     dataSource.setUser("user"); 
     dataSource.setMaxConnections(10); 
     return dataSource; 
    } 
}