Out of container JNDI data source

佐手、 提交于 2019-11-30 11:28:53

Why are you using JNDI for this? It's not that it's a bad solution if you have a provider but there are alternatives such as dependency injection (IoC: via Spring or Guice).

The Spring JDBC data access is described here. The great thing is that you can use Spring to inject a DataSource into your code:

<bean class="com.my.Persister">
    <property name="dataSource" ref="dataSource" />
</bean>

The data source can be defined using a JNDI-lookup:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource" /> 

In a test environment, you could inject the data source directly:

<bean id="dataSource" class="apache.db.PoolingDataSource">
    <!-- config goes here -->
</bean>

These references are pretty old but may help to use jnpserver (JBoss Naming Service provider):

A very easy to use solution for stand-alone JNDI is simple-jndi. It works like a charm as long as you only need it within a single JVM, since it's a library no network server.

The Simple-JNDI version, referenced by klenkes74, is not under active development any more. Because I encountered some issues with it I forked it, did some bug fixes and implemented some new features. I already used the old version not only for testing but in production too because I prefer a Service Locator pattern over Dependency Injection although the latter one is more trendy nowadays.

You can easily use Simple-JNDI to define a DataSource or a connection pool declaratively and get it bound to a JNDI Context.

Define a jndi.properties file in your classpath:

java.naming.factory.initial=org.osjava.sj.SimpleContextFactory
org.osjava.sj.root=[absolute_or_relative_path_to_a_property_file]

The property file looks like:

type=javax.sql.DataSource
driver=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost/testdb
user=testuser
password=testing

Now you can access your DataSource from inside your code this way:

  InitialContext ctxt = new InitialContext();
  DataSource ds = (DataSource) ctxt.lookup("name_of_your_datasource");

For more information see https://github.com/h-thurow/Simple-JNDI

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!