答案 0 :(得分:10)
据我所知,对你来说真正有用的是JndiObjectFactoryBean。此Spring工厂bean返回在JNDI中发布的对象。
您可以像这样进行配置,然后在注入的Connection
上使用DataSourceUtils
获得DataSource
:
<bean name="myDataSourceInJndi" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/MyDataSource</value>
</property>
</bean>
<bean name="myBean" class="MyClass">
...
<property name="dataSource" ref="myDataSourceInJndi">
...
</bean>
答案 1 :(得分:3)
嗯......不知怎的,DataSourceUtils
的Javadoc更“准确”(我的意思是,doc没有错,但从技术上讲,你从DataSource获得连接 - 可以通过JNDI获得):
Helper类,提供从
DataSource
获取JDBC连接的静态方法。
以下方法应该是您正在寻找的方法:
基本示例(来自MySQL documentation):
// Create a new application context. this processes the Spring config
ApplicationContext ctx = new ClassPathXmlApplicationContext("ex1appContext.xml");
// Retrieve the data source from the application context
DataSource ds = (DataSource) ctx.getBean("dataSource");
// Open a database connection using Spring's DataSourceUtils
Connection c = DataSourceUtils.getConnection(ds);
try {
// retrieve a list of three random cities
PreparedStatement ps = c.prepareStatement(
"select City.Name as 'City', Country.Name as 'Country' " +
"from City inner join Country on City.CountryCode = Country.Code " +
"order by rand() limit 3");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
String city = rs.getString("City");
String country = rs.getString("Country");
System.out.printf("The city %s is in %s%n", city, country);
}
} catch (SQLException ex) {
// something has failed and we print a stack trace to analyse the error
ex.printStackTrace();
// ignore failure closing connection
try { c.close(); } catch (SQLException e) { }
} finally {
// properly release our connection
DataSourceUtils.releaseConnection(c, ds);
}
答案 2 :(得分:0)
以备将来参考:jndi在应用服务器上管理,即:带有Postgresql驱动程序的standalone.xml(Wildfly):
<datasource jta="true" jndi-name="java:comp/env/jdbc/MyDataSource" pool-name="myDS" enabled="true">
<connection-url>jdbc:postgresql:[<//host>[:<5432>/]]<database></connection-url>
<driver>postgresql</driver>
<security>
<user-name>$USER</user-name>
<password>$PWD</password>
</security>
</datasource>