我再次搜索这个问题,我无法使用 java config 找到 jndi 数据库。在此之前,我使用 xml 并且它工作得很好,但在 java 配置中它会导致问题;
XML 代码:
<!-- Jndi database connection -->
<jee:jndi-lookup id="dbDataSource" jndi-name="${db.jndi}"
resource-ref="true" />
<beans:bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate" >
<beans:property name="dataSource" ref="dbDataSource"></beans:property>
</beans:bean>
现在的 Java 配置:
@Bean(name = "dbDataSource")
public DataSource dataSource(@Value("${db.jndi}") String jndiName)
{
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
return lookup.getDataSource(jndiName);
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
属性文件:
db.jndi=jndi/myData
weblogic 中的 JNDI 名称:
jndi/myData
更改java配置后,有时系统可以读取数据库,但很少发生,直到我清理并重新启动计算机才可以找到数据库,但通常总是触发:
javax.naming.NameNotFoundException:无法解析“jndi.myData”。解决了“jndi”;剩余名称“myData”
为什么应用程序无法正确找到数据库? 谢谢!!!
最佳答案
我也遇到过同样的问题。如果您使用的是 4.x 版本的 spring,这可能就是原因。
您还应该check Weblogic's JNDI Tree 。如果重建项目后您的数据源从树中消失,这是另一个症状
如果是这样的话,发生的事情是:
Your Datasource implements Closeable (and therefore AutoCloseable) and the context will always invoke the shutdown method regardless of your Bean definition
它已被标记为文档问题,因为这是“预期”行为:
This issue was solely about documentation since we decided not to implement anything at the framework level
解决办法,将bean的destroy方法定义为空,如:
@Bean(name = "dbDataSource", destroyMethod="")
public DataSource dataSource(@Value("${db.jndi}") String jndiName)
{
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
return lookup.getDataSource(jndiName);
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource ds) {
return new JdbcTemplate(ds);
}
这在 issue (SPR-13022:Destroy callback cannot be disabled for AutoCloseable beans) 中有描述。 .
PS:顺便说一下,在 spring 的早期 4.x 版本中,您似乎无法通过分配 destroyMethod 来覆盖此行为。看来这个bug已经在4.2 RC1版本中修复了。
关于spring - java配置中出现Weblogic jndi NameNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846843/