代码之家  ›  专栏  ›  技术社区  ›  Synesso

在springjdbc中通过JNDI获得JDBC连接

  •  6
  • Synesso  · 技术社区  · 14 年前

    这个 page on Spring JDBC

    the API doc for DataSourceUtils 据我所知,不包括上述静态方法。

    3 回复  |  直到 14 年前
        1
  •  3
  •   Pascal Thivent    14 年前

    隐马尔可夫模型。。。不知怎的 DataSourceUtils

    Helper类,该类提供用于从 DataSource .

    你要找的方法应该是:

    基本示例(来自 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);
    }
    
        2
  •  10
  •   gpeche    14 年前

    据我所知,对你真正有用的是 JndiObjectFactoryBean . 这个Spring工厂bean返回JNDI中发布的对象。

    你可以这样配置它,然后得到 Connection DataSourceUtils 在注入的 DataSource :

    <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>
    
        3
  •  0
  •   molino.bruno    7 年前

    供将来参考:jndi在应用服务器上管理,即:独立.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>