0

我有一个在外部 tomcat 上配置了数据源的 spring boot 应用程序,如何将外部 tomcat 配置的数据源的 driverClassName 获取到我的 spring boot 应用程序中。

我试着写一些代码

PoolProperties poolProps = new PoolProperties();
Properties dbProperties = poolProps.getDbProperties();
String databaseUrl = dbProperties.getProperty("databaseUrl");

但是上面代码中的databaseUrl返回null。谁能建议我如何将 driverClassName 放入我的 java 代码中?

4

2 回答 2

0

为什么不使用 JNDI 名称?

spring.datasource.jndi-name=<the name configured in tomcat>
于 2021-04-06T19:09:16.750 回答
0

您可以通过反射检索数据源的 JavaBean 属性。只需使用有助于自省的众多工具之一。

由于您已经具有spring-beans依赖项,因此可以使用:

final BeanWrapper accessor = PropertyAccessorFactory.forBeanPropertyAccess(dataSource);
final String url = String.valueOf(accessor.getPropertyValue("url"));

你也可以直接使用反射,但它变得容易阅读困难:

try {
    final String value = String.valueOf(dataSource.getClass().getMethod("getUrl").invoke(dataSource));
} catch (ReflectiveOperationException e) {
    ...
}
于 2021-04-06T21:09:35.063 回答