OSGI 容器中的数据源

DataSource in an OSGI container

我有一个简单的 Spring 应用程序,它通过 EntityManager

连接到数据库

所以我必须进行以下配置:

<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="TheManager" />
    <property name="dataSource" ref="domainDataSource" />
    <property name="packagesToScan" value="com.conztanz.persistence.stock.model" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        </props>
    </property>
</bean>


<bean id="domainDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5433/dbName" />
    <property name="username" value="xxxx" />
    <property name="password" value="xxxx" />
</bean>

这在通过 main class(手动加载 AppContext)午餐时工作正常

但是,一旦部署到 ServiceMix,我就会收到以下错误:

Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [org.postgresql.Driver]

DriverManager 在 OSGi 中运行不佳。最简单的方法是直接使用数据源。大多数数据库驱动程序都有这样一个 class。如果您在您的应用程序上下文中实例化它,那么它将起作用。缺点是它将您的应用程序绑定到数据库驱动程序,因为它将导入数据源实现的包。

一种更松耦合的方式是使用ops4j pax jdbc。它允许从配置管理中的配置创建一个数据源作为 OSGi 服务。因此,在您的应用上下文中,您只需添加对 DataSource 服务的依赖。所以你的应用程序没有绑定到特定的数据库驱动程序。一个典型的用例是在测试中使用 H2,在生产中使用 oracle。