如何在Datasource.groovy中获取服务器名称(如Tomcat、WebLogic)
Got it, let's figure out how to get server info in your Datasource.groovy file—since you can’t directly use getServletContext().getServerInfo() there like you do in controllers, we need to use early-available Java APIs instead. Here are practical approaches tailored to your needs:
Option 1: Get the Hostname of the Deployment Server
If you need to distinguish between different physical/virtual servers (e.g., dev, test, prod hosts), use Java’s InetAddress class to fetch the server’s hostname directly:
import java.net.InetAddress // Fetch the server hostname def serverHostname = InetAddress.getLocalHost().getHostName() // Use it to conditionally configure your datasource environments { production { dataSource { if (serverHostname == "prod-db-primary") { url = "jdbc:mysql://primary-db:3306/app_db" username = "prod_user" password = "prod_pass" } else if (serverHostname == "prod-db-secondary") { url = "jdbc:mysql://secondary-db:3306/app_db" username = "prod_readonly_user" password = "prod_readonly_pass" } driverClassName = "com.mysql.cj.jdbc.Driver" dialect = org.hibernate.dialect.MySQL8Dialect } } }
Note: Ensure your server’s /etc/hosts (or equivalent) is configured correctly—if not, getLocalHost() might return localhost instead of the actual hostname. For containerized environments (Docker/K8s), this might return the container ID, so consider passing a custom server identifier via environment variables instead:
// Fall back to hostname if env var isn't set def serverIdentifier = System.getenv("SERVER_IDENTIFIER") ?: InetAddress.getLocalHost().getHostName()
Option 2: Detect the Application Server Type (Tomcat/Jetty, etc.)
If you need to adjust logic based on which app server you’re running (e.g., Tomcat vs. Jetty), check system properties that each server exposes:
// Fetch server info system property (set by most app servers) def serverInfo = System.getProperty("server.info") // Check for specific server types def isTomcat = serverInfo?.startsWith("Apache Tomcat") def isJetty = serverInfo?.startsWith("Jetty") // Apply server-specific datasource configs if (isTomcat) { dataSource { // Tomcat-specific settings, like connection pool tweaks maxActive = 100 maxIdle = 20 } } else if (isJetty) { dataSource { // Jetty-specific connection pool configs maxTotal = 100 maxIdlePerKey = 20 } }
Other server-specific properties you can use:
- Tomcat:
catalina.baseorcatalina.home - Jetty:
jetty.home - WildFly:
jboss.home.dir
Why getServletContext() Doesn’t Work Here
Remember, Datasource.groovy loads very early in the Grails application lifecycle—way before the ServletContext is initialized. That’s why controller-level methods won’t work here; we have to rely on Java APIs that are available at JVM startup.
内容的提问来源于stack exchange,提问作者Ramesh

