更改 JNDI 检索到的数据源的属性



数据源在应用程序服务器(Jboss(上配置

<subsystem xmlns="urn:jboss:domain:datasources:1.2">
<datasources>
<datasource jta="true" jndi-name="java:/TestDataSource" pool-name="TestDataSource" enabled="true" use-ccm="true" statistics-enabled="false">
<connection-url>...</connection-url>
<driver-class>com.informix.jdbc.IfxDriver</driver-class>
<driver>informix</driver>
<new-connection-sql>set lock mode to wait 15</new-connection-sql>
<transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>30</max-pool-size>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
<security>
<user-name>...</user-name>
<password>...</password>
</security>
<validation>
<check-valid-connection-sql>...</check-valid-connection-sql>
<validate-on-match>true</validate-on-match>
<background-validation>true</background-validation>
</validation>
<timeout>
<set-tx-query-timeout>false</set-tx-query-timeout>
<blocking-timeout-millis>0</blocking-timeout-millis>
<idle-timeout-minutes>5</idle-timeout-minutes>
<query-timeout>0</query-timeout>
<use-try-lock>0</use-try-lock>
<allocation-retry>0</allocation-retry>
<allocation-retry-wait-millis>0</allocation-retry-wait-millis>
</timeout>
<statement>
<prepared-statement-cache-size>100</prepared-statement-cache-size>
<share-prepared-statements>true</share-prepared-statements>
</statement>
</datasource>
</subsystem>

使用 JNDI 检索数据源。在将其作为 bean 返回之前,我想更改 url 和驱动程序类。所有其他配置的属性应保持不变。数据源接口不提供资源库来实现此目的。对于此类任务,最佳解决方案是什么?

@Configuration
public class DBConfig {
@Value("${datasource.test}")
private String dataSourceProperty;
@Bean
public DataSource dataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("java:/" + dataSourceProperty);
// here before returning the datasource I would like to change the url and database driver, other configs should remain unchanged
return dataSource;
}
}

你需要将 DataSource 接口强制转换为具体实现(例如,org.apache.tomcat.jdbc.pool.DataSource(,然后只需使用具体类的 setter 方法:

org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = (org.apache.tomcat.jdbc.pool.DataSource)dataSource;
tomcatDataSource.setUrl("...");

最新更新