Spring:如何在Groovy DAO中以编程方式配置tomcat Datasource

时间:2015-06-06 06:10:47

标签: java spring spring-mvc tomcat groovy

我的XML配置了我的tomcat数据源,如下所示:

<bean id="docDataSource"
    class="org.apache.tomcat.jdbc.pool.DataSource" 
    destroy-method="close"
    p:driverClassName="${doc.database.driver}" 
    p:url="${doc.database.url}"
    p:username="${doc.database.user}" 
    p:password="${doc.database.password}"
    p:validationQuery="select 1" 
    p:testOnBorrow="true" 
    p:minIdle="2" 
    p:maxIdle="4" 
    p:maxActive="6" 
    p:defaultTransactionIsolation="1">
</bean>

我的customDAO(groovy类)使用上面的数据源

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import groovy.sql.Sql
import org.apache.log4j.Level
import javax.sql.DataSource
import java.util.Map
import java.util.Map.Entry
import java.util.ResourceBundle

@Component
public class customDao implements GroovyInterceptable {

    @Autowired
    private Services services

    @Autowired
    @Qualifier("docDataSource")
    private DataSource            dataSource
   // implementation    
}

我想将我的tomcat dataSource切换为类文件而不是XML。有人可以帮我怎么做吗?

1 个答案:

答案 0 :(得分:1)

这是你可以遵循的一段代码(使用PostgreSQL,但它应该或多或少地工作相同):

import org.postgresql.ds.PGPoolingDataSource
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

import javax.sql.DataSource

@Configuration
class PostgreSQLDatasourceConfiguration {

  @Bean(name = 'dataSource')
  DataSource ds(@Value('${DATABASE_URL}') String databaseFullUrl) {
    assert databaseFullUrl, 'Database URL is required to start the application'

    URI uri = new URI(databaseFullUrl)
    def (_, dbUsername, dbPassword) = (uri.getUserInfo() =~ /(.*):(.*)/)[0]

    (DataSource) new PGPoolingDataSource().tap {
      url = "jdbc:postgresql://$uri.host:${uri.port}$uri.path"
      password = dbPassword
      user = dbUsername
    }
  }
}