2010-09-08 129 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>