【发布时间】:2015-11-16 04:12:01
【问题描述】:
我在 Apache Karaf 3.0.4 中工作,我的问题是当我尝试从数据源(我有一个数据源列表)获取属性时出现错误,我正在使用此代码
BundleContext bundleContext = FrameworkUtil.getBundle(MyController.class).getBundleContext();
ServiceReference[] serviceReferences =bundleContext.getAllServiceReferences("javax.sql.DataSource", null);
//and in this part
for (ServiceReference serviceReference : serviceReferences) {
Object jndi = serviceReference.getProperty("osgi.jndi.service.name");
if (jndi != null) {
serviceReferenceDataSources.add(serviceReference);
Object service = bundleContext.getService(serviceReference);
//here the code fails
BasicDataSource basicDataSource = (BasicDataSource) service;
}
}
这是堆栈跟踪
java.lang.ClassCastException: Proxyfcb4dd22_6103_4978_b41b_0bacfb118a66 cannot be cast to org.apache.commons.dbcp2.BasicDataSource
我需要 BasicDataSource 对象来获取它们的属性(maxTotal、用户名、url、validationQuery、initialSize、maxWaitMillis)
最后,当我尝试强制转换为“javax.sql.DataSource”时,此代码有效,但我需要此对象 BasicDataSource。
编辑 1
这是我的蓝图
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
xsi:schemaLocation="
http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.0.0.xsd
http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="maxTotal" value="${jdbc.maxTotal}" />
<property name="maxWaitMillis" value="${jdbc.maxWaitMillis}" />
<property name="validationQuery" value="${jdbc.validationQuery}"/>
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
</bean>
<service interface="javax.sql.DataSource" ref="dataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="jdbc/ejemplodb"/>
<entry key="datasource" value="ejemplodb"/>
</service-properties>
</service>
如果我在控制台中打印此代码
...
Object service = bundleContext.getService(serviceReference);
logger.debug("Service getClass() ", service.getClass());
System.out.println("Service in println" + service);
...
我明白了
Service getClass() Proxy79d23ceb_cee2_4031_bdc3_13fd572cdf8c
Service in println org.apache.commons.dbcp2.BasicDataSource@7f753504
希望你能帮助我,谢谢。
【问题讨论】:
-
请从 BasicDataSource 中定义您需要的数据源无法在此处提供的内容。
-
我需要获取所有 BasicDataSource 属性,我正在创建一个包来测试我的数据源是否存在,使用验证查询,并且我在 Web 服务中公开数据。
标签: java datasource karaf