简单的说,程序员可以使用同一个JNDI接口来查询以下内容
简单介绍就到这里
应用程序服务器的资源放置在“java:comp/env”前缀下。假设数据源已开启
java:/comp/env/jdbc/db1
获取该数据源
javax.naming.Context initialContext = new javax.naming.InitialContext(); javax.naming.Context subContext = (javax.naming.Context) initialContext.lookup("java:comp/env"); DataSource dataSource = (DataSource) subContext.lookup("jdbc/db1");
或者您可以通过提供完整路径直接获取实例
javax.naming.Context initialContext = new javax.naming.InitialContext(); DataSource dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/db1");
只需在application.properties
中添加一行
spring.datasource.jndi-name=java:/comp/env/jdbc/db1
相关bean由org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration
创建
@Configuration(proxyBeanMethods = false) @AutoConfigureBefore({ XADataSourceAutoConfiguration.class, DataSourceAutoConfiguration.class }) @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }) @ConditionalOnProperty(prefix = "spring.datasource", name = "jndi-name") @EnableConfigurationProperties(DataSourceProperties.class) public class JndiDataSourceAutoConfiguration { @Bean(destroyMethod = "") @ConditionalOnMissingBean public DataSource dataSource(DataSourceProperties properties, ApplicationContext context) { JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); DataSource dataSource = dataSourceLookup.getDataSource(properties.getJndiName()); excludeMBeanIfNecessary(dataSource, "dataSource", context); return dataSource; } private void excludeMBeanIfNecessary(Object candidate, String beanName, ApplicationContext context) { for (MBeanExporter mbeanExporter : context.getBeansOfType(MBeanExporter.class).values()) { if (JmxUtils.isMBean(candidate.getClass())) { mbeanExporter.addExcludedBean(beanName); } } } }
以上是快速浏览JNDI(Java命名和目录接口)的详细内容。更多信息请关注PHP中文网其他相关文章!