You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不通过WildFly管理数据库,使用JNDI配置PostgreSQL是否可行?

Alternative JNDI-Based PostgreSQL Configurations Without WildFly Management

Absolutely! You don’t have to depend on WildFly’s admin console or server-level config files (like standalone.xml/domain.xml) to set up JNDI access for PostgreSQL. Here are two practical, application-controlled approaches to get this done:

1. Embedded JNDI Context with Custom Connection Pooling

You can spin up your own JNDI context directly within your application and bind a PostgreSQL connection pool to it—no WildFly server configuration required. Libraries like HikariCP or Apache Commons DBCP2 work perfectly here for robust pooling.

Step-by-Step Example:

  • First, add the required dependencies to your build file (Maven example below):
    <!-- PostgreSQL JDBC Driver -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.6.0</version>
    </dependency>
    <!-- HikariCP Connection Pool -->
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>5.0.1</version>
    </dependency>
    <!-- Lightweight JNDI Implementation -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jndi</artifactId>
        <version>10.1.10</version>
        <scope>provided</scope>
    </dependency>
    
  • Create a startup listener (for web apps) to initialize the JNDI context and bind your data source:
    import com.zaxxer.hikari.HikariConfig;
    import com.zaxxer.hikari.HikariDataSource;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    
    @WebListener
    public class JndiDataSourceInitializer implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            try {
                // Configure HikariCP pool
                HikariConfig poolConfig = new HikariConfig();
                poolConfig.setJdbcUrl("jdbc:postgresql://localhost:5432/your_database");
                poolConfig.setUsername("your_db_user");
                poolConfig.setPassword("your_db_password");
                poolConfig.setDriverClassName("org.postgresql.Driver");
                poolConfig.setMaximumPoolSize(10); // Adjust based on your needs
    
                HikariDataSource dataSource = new HikariDataSource(poolConfig);
    
                // Set up embedded JNDI context
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
                System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
                InitialContext jndiContext = new InitialContext();
                
                // Create subcontext and bind the data source
                jndiContext.createSubcontext("java:comp/env/jdbc");
                jndiContext.bind("java:comp/env/jdbc/PostgresDS", dataSource);
            } catch (NamingException e) {
                throw new RuntimeException("Failed to initialize JNDI data source", e);
            }
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // Clean up the pool on app shutdown
            try {
                InitialContext jndiContext = new InitialContext();
                HikariDataSource dataSource = (HikariDataSource) jndiContext.lookup("java:comp/env/jdbc/PostgresDS");
                dataSource.close();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }
    
  • Now you can look up the data source anywhere in your app using standard JNDI syntax:
    InitialContext context = new InitialContext();
    DataSource postgresDS = (DataSource) context.lookup("java:comp/env/jdbc/PostgresDS");
    

2. Application-Level Java EE Resource Configuration

If you’re using Java EE, you can define the PostgreSQL data source directly in your application’s deployment descriptors. WildFly will recognize these settings without needing any server-level admin changes.

Example Setup:

  • First, either package the PostgreSQL driver in your app’s WEB-INF/lib directory or add it as a WildFly module (the module approach avoids duplicate driver conflicts).
  • Add a resource reference to your web.xml:
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="4.0">
        <resource-ref>
            <description>PostgreSQL Application Data Source</description>
            <res-ref-name>jdbc/PostgresDS</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
        </resource-ref>
    </web-app>
    
  • Create a jboss-web.xml (WildFly-specific) to map the resource reference to an app-scoped JNDI name:
    <jboss-web xmlns="http://www.jboss.com/xml/ns/javaee" version="8.0">
        <resource-ref>
            <res-ref-name>jdbc/PostgresDS</res-ref-name>
            <jndi-name>java:app/PostgresDS</jndi-name>
        </resource-ref>
    </jboss-web>
    
  • Define the data source and connection pool in a glassfish-resources.xml (WildFly supports this standard file):
    <resources xmlns="http://glassfish.org/xmlns/resources">
        <jdbc-resource jndi-name="java:app/PostgresDS" pool-name="PostgresAppPool"/>
        <jdbc-connection-pool name="PostgresAppPool" res-type="javax.sql.DataSource">
            <property name="driverClass" value="org.postgresql.Driver"/>
            <property name="url" value="jdbc:postgresql://localhost:5432/your_database"/>
            <property name="user" value="your_db_user"/>
            <property name="password" value="your_db_password"/>
            <property name="maxPoolSize" value="10"/>
            <property name="minPoolSize" value="2"/>
        </jdbc-connection-pool>
    </resources>
    
  • Package all these files with your WAR/EAR, and WildFly will deploy the data source alongside your application automatically.

Quick Tips:

  • For the embedded JNDI approach, you have full control over credentials and pool settings—they’re stored within your app, not in WildFly’s server config.
  • If you package the PostgreSQL driver with your app, ensure it’s not conflicting with any driver modules already installed in WildFly.

内容的提问来源于stack exchange,提问作者Igor Gorbunov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:09:39