简单的说,程序员可以使用同一个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); } } } }
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3