簡單的說,程式設計師可以使用同一個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