airfox
airfox

Reputation: 137

Override property in application.groovy with external config in grails 3

There is no grails.config.locations property in grails 3 anymore, now Grails 3 uses Spring's property source concept instead, but how can I achieve the same behavior in grails 3 as it was in previous versions? Suppose I want to override some property property.to.be.overridden in application.grovy file with my external configuration file. How can I do it?

Upvotes: 6

Views: 3010

Answers (2)

SGT Grumpy Pants
SGT Grumpy Pants

Reputation: 4436

I solved this a slightly different way, so I could load an external YAML file.

Application.groovy

package com.mycompany.myapp

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean
import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.core.env.PropertiesPropertySource
import org.springframework.core.io.FileSystemResource
import org.springframework.core.io.Resource;

class Application extends GrailsAutoConfiguration implements EnvironmentAware {
    static void main(String[] args) {
        GrailsApp.run(Application)
    }

    @Override
    void setEnvironment(Environment environment) {
        String configPath = System.properties["myapp.config.location"]
        if (configPath) {
            Resource resourceConfig = new FileSystemResource(configPath);
            YamlPropertiesFactoryBean propertyFactoryBean = new YamlPropertiesFactoryBean();
            propertyFactoryBean.setResources(resourceConfig);
            propertyFactoryBean.afterPropertiesSet();
            Properties properties = propertyFactoryBean.getObject();
            environment.propertySources.addFirst(new PropertiesPropertySource("myapp.config.location", properties))
        }
    }
}

Then I specify the YAML file when I run it

command line

java -jar -Dmyapp.config.location=/etc/myapp/application.yml build/libs/myapp-0.1.war

Upvotes: 0

Zergleb
Zergleb

Reputation: 2312

The equivalent of grails.config.locations is spring.config.location

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-application-property-files

Here is an example specifying configuration locations while launching a jar from the command line(These same arguments can be used inside of your ide)

 java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

Also since you mention wanting to override properties it's useful to learn the way Spring Boot handles profile specific property files(Multiple profiles may also be specified)

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties

Upvotes: 3

Related Questions