46619

How to load datasource configuration from external file in grails 3.1.8?

I am writing a grails 3.1.8 application. My datasource written in application.groovy file.

I want to load datasource configuration like username,password,DB from an external file. Is there any way to do it in grails 3+ versions.

Here is my datasource configuration in application.groovy:-

hibernate { cache { queries = false use_second_level_cache = true use_query_cache = false region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' } } dataSource { pooled = true jmxExport = true dialect = 'org.hibernate.dialect.PostgreSQLDialect' driverClassName = 'org.postgresql.Driver' username = 'postgres' password = 'postgres' properties = { jmxEnabled = true initialSize = 5 maxActive = 50 minIdle = 5 maxIdle = 25 maxWait = 10000 maxAge = 10 * 60000 timeBetweenEvictionRunsMillis = 5000 minEvictableIdleTimeMillis = 60000 validationQuery = "SELECT 1" validationQueryTimeout = 3 validationInterval = 15000 testOnBorrow = true testWhileIdle = true testOnReturn = false ignoreExceptionOnPreLoad = true jdbcInterceptors = "ConnectionState;StatementCache(max=200)" defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED // safe default abandonWhenPercentageFull = 100 // settings are active only when pool is full removeAbandonedTimeout = 120 removeAbandoned = true logAbandoned = false // causes stacktrace recording overhead, use only for debugging } } environments { development { dataSource { dbCreate = 'update' url = "jdbc:postgresql://localhost:5432/testdb" logSql = true } } test { dataSource { dbCreate = 'update' url = "jdbc:postgresql://localhost:5432/testdb" logSql = true } } production { dataSource { dbCreate = 'update' url = "jdbc:postgresql://localhost:5432/testdb" logSql = true } } }

Answer1:

Here is the solution that worked for me, you can try.

This solution will work for grails 3.0+

First of all need to add following dependency:

<strong>compile 'org.grails.plugins:external-config:1.1.2'</strong>

then need to create external configuration groovy file for example:

<strong>db-config.groovy</strong>

then need to place that config file into outside of the application directory or tomcat library. for example:

<strong>D:\apache-tomcat-8.0.47\lib</strong>

Then need to read config file from the <strong>application.groovy</strong> . In <strong>application.groovy</strong> need to place following line of code for each environment:

<strong>grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy']</strong>

or

<strong>grails.config.locations = ['file:///D:/apache-tomcat-8.0.47/lib/db-config.groovy']</strong>

You can use <strong>${catalina.home}</strong> if you set the environment variable is <strong>CATALINA_HOME</strong> in your system. Other than you have to use direct path that I showed.

So your <strong>application.groovy</strong> will be following:

> environments { > development { > grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy'] > } > production { > grails.config.locations = ['file:///${catalina.home}/lib/db-config.groovy'] > ] > } > }

and your <strong>db-config.groovy</strong> file will contain following lines:

> dataSource { > username = <DB_USER_NAME> > password = <DB_PASSWORD> > dbCreate = 'update' > url = <DB_URL> > logSql = true > }

You can use different db-config.groovy file for each environment.

Answer2:

You can load your external configuration file from file system using the following implementation.

This example defines for each environment( development / production / test) a separate path to an external config file.

environments { development { grails.config.locations = [ "file:///home/<CONFIG_FILE_LOCATION_DIR>/myconfig_developement.groovy" //for Unix based systems ] } production { grails.config.locations = [ "file:///home/<CONFIG_FILE_LOCATION_DIR>/myconfig_production.groovy" // for Unix based systems ] } }

Put your database configuration in myconfig_developement.groovy as follows:

dataSource { dbCreate = 'update' url = "jdbc:postgresql://localhost:5432/testdb" logSql = true }

Answer3:

You can use this solution (that worked for me, with grails 3.1.x)

grails-app/init/Application.groovy:

class Application extends GrailsAutoConfiguration implements EnvironmentAware { static void main(String[] args) { GrailsApp.run(Application, args) } @Override void setEnvironment(Environment environment) { def path = "/etc/grails-app-config.properties" def file = new File(path) if(file.exists()) { def config = new ConfigSlurper().parse(file.text) environment.propertySources.addFirst(new MapPropertySource(grails.util.Environment.getCurrent().name, config)) } } }

you can use environment variable for the config path:

System.getenv(ENV_CONF_FILE_VAR)

grails-app-config.properties:

dataSource.dbCreate='update' dataSource.driverClassName='com.mysql.jdbc.Driver' dataSource.url='jdbc:mysql://localhost:5432/testdb' dataSource.username='user' dataSource.password='pass' com.test='test' com.numTest=4

Answer4:

You can use external-config Grails plugin and define the configuration in your external configuration file.

grails.config.locations = [ "file:///etc/app/myconfig.groovy" ]

And then define datasource configuration in myconfig.groovy

Recommend

  • Using Node cluster module with SailsJs: EADDRINUSE
  • Sending emails over SMTP with TSL
  • Yahoo finance historical stock price power query returns 301 response
  • How to access data/data files of Android without a terminal on the Android device
  • How to silently drop a request in Tomcat?
  • IllegalStateException “System services not available to Activities before onCreate()”
  • Errno::ECONNREFUSED No connection could be made because
  • How to run requests.get asynchronously in Python 3 using asyncio?
  • String encoding problem on PdoStatement->bindParam()?
  • Send Tor NEWNYM request using Java
  • ORA-12154: TNS:could not resolve the connect identifier specified
  • Argument 5: cannot convert from 'System.Drawing.Image' to 'string' - calling cla
  • twisted.internet.error.ConnectError when run scrapy spider
  • openssl handshake failed
  • Connecting Google Cloud SQL with Wordpress on Google Compute Engine
  • Install phpMongo Drivers on windows
  • Changing media screen makes div overlay
  • I am receiving HibernateException “No Hibernate Session bound to thread, and configuration does not
  • How can Delete be both a DDL and a DML statement
  • Cloud Code function running twice
  • How to 'create temp table as select' in Slick?
  • what makes a request a new request in asp.net C#
  • RxJava debounce by arbitrary value
  • pyodbc doesn't report sql server error
  • Check for zero lines output from command over SSH
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • D3 get axis values on zoom event
  • C: Incompatible pointer type initializing
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • How to create a file in java without a extension
  • OpenGL ES texture problem, 4 duplicate columns and horizontal lines (Android)
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • PHP - How to update data to MySQL when click a radio button
  • Counter field in MS Access, how to generate?
  • Cross-Platform Protobuf Serialization
  • Display Images one by one with next and previous functionality
  • How to get next/previous record number?
  • How to format a variable of double type
  • coudnt use logback because of log4j
  • JaxB to read class hierarchy