簡單的說,程式設計師可以使用同一個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中文網其他相關文章!