2016-07-30 70 views
0

我從here下載了fscontext.jar文件,並將其放入我的類路徑中。從獨立Java應用程序中的JNDI上下文獲取DataSource對象?

這是我的代碼:

import javax.naming.*; 
import java.io.File; 

public class JNDIHello { 

    final static String URL = 
      "file:///Users/Koray Tugay/Development/studentform/src/main/java/biz/tugay"; 
    final static String CONTEXT_FACTORY 
      = "com.sun.jndi.fscontext.RefFSContextFactory"; 

    static { 
     System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY); 
     System.setProperty(Context.PROVIDER_URL, URL); 
    } 

    public static void main(String[] args) throws Exception { 
     final InitialContext context = new InitialContext(); 
     final File file = (File) context.lookup("TestClass.java"); 
     System.out.println("File exists? " + file.exists()); 
    } 
} 

輸出將是:

File exists? true 

這是偉大的。我將RefFSContextFactory與JNDI一起使用,從上下文獲取文件對象

我想要做的就是能夠獲得DataSource對象,就像在web應用程序中一樣。一個例子可以看到here

我已經h2db在我的本地運行和屬性的情況如下:

<?xml version='1.0' encoding='utf-8'?> 
<Context> 
    <Resource name="jdbc/studentform" auth="Container" type="javax.sql.DataSource" 
       maxActive="5" maxIdle="10" maxWait="10000" 
       username="sa" password="" driverClassName="org.h2.Driver" 
       url="jdbc:h2:tcp://localhost:9092/~/h2dbs/studentform"/> 
</Context> 

但我應該用什麼JNDI工廠實現和怎樣在一個獨立的Java應用程序定義的網址是什麼?

回答

0

你需要一些容器來運行你的應用程序,並提供諸如數據源管理等服務。Spring Framework是在這種情況下首先想到的。它允許你創建一個IoC容器來管理你的依賴關係,including data sources。它還有Spring Boot子項目,可以更容易地創建可運行模塊。

相關問題