2010-09-08 174 views

回答

3

嗯......不知何故,中DataSourceUtils的Javadoc更「準確」(我的意思是,美國商務部並沒有錯,但在技術上,您將獲得從數據源的連接 - 可以通過JNDI獲得):

幫助程序類,它提供從DataSource獲取JDBC連接的靜態方法。

而下面的方法應該是你在找什麼:

基本示例(從MySQL documentation):

// Create a new application context. this processes the Spring config 
ApplicationContext ctx = new ClassPathXmlApplicationContext("ex1appContext.xml"); 
// Retrieve the data source from the application context 
DataSource ds = (DataSource) ctx.getBean("dataSource"); 
// Open a database connection using Spring's DataSourceUtils 
Connection c = DataSourceUtils.getConnection(ds); 
try { 
    // retrieve a list of three random cities 
    PreparedStatement ps = c.prepareStatement(
     "select City.Name as 'City', Country.Name as 'Country' " + 
     "from City inner join Country on City.CountryCode = Country.Code " + 
     "order by rand() limit 3"); 
    ResultSet rs = ps.executeQuery(); 
    while(rs.next()) { 
     String city = rs.getString("City"); 
     String country = rs.getString("Country"); 
     System.out.printf("The city %s is in %s%n", city, country); 
    } 
} catch (SQLException ex) { 
    // something has failed and we print a stack trace to analyse the error 
    ex.printStackTrace(); 
    // ignore failure closing connection 
    try { c.close(); } catch (SQLException e) { } 
} finally { 
    // properly release our connection 
    DataSourceUtils.releaseConnection(c, ds); 
} 
10

據我所知,對你來說真正有用的是JndiObjectFactoryBean。這個Spring工廠bean返回在JNDI中發佈的對象。

你會配置它這樣的,然後你會在注射DataSource使用DataSourceUtils得到Connection

<bean name="myDataSourceInJndi" class="org.springframework.jndi.JndiObjectFactoryBean"> 
    <property name="jndiName"> 
     <value>java:comp/env/jdbc/MyDataSource</value> 
    </property> 
</bean> 

<bean name="myBean" class="MyClass"> 
... 
    <property name="dataSource" ref="myDataSourceInJndi">   
... 
</bean> 
+0

嗨,我是新來春天,我想知道如果我用你上面提到的方法,我在哪裏存儲'username'和'password'爲我的連線? – 2016-02-17 15:51:30

0

爲今後進一步的參考文獻:JNDI是應用服務器,即管理:standalone.xml (Wildfly)與PostgreSQL驅動:

<datasource jta="true" jndi-name="java:comp/env/jdbc/MyDataSource" pool-name="myDS" enabled="true"> 
       <connection-url>jdbc:postgresql:[<//host>[:<5432>/]]<database></connection-url> 
       <driver>postgresql</driver> 
       <security> 
        <user-name>$USER</user-name> 
        <password>$PWD</password> 
       </security> 
      </datasource>