How to define properties of a Service Bean from application.yml in Grails 3?

746 Views Asked by At

I was able to define properties of a service bean from Config.groovy.

Quoting Book The Definitive Guide to Grails 2

Listing 10-6. Configuring Beans Using Config.groovy

beans {
    albumArtService {
        artworkRequestUrl = 'http://itunes...'
    }
}

One advantage of this approach is that thanks to the features offered by Config.groovy, you can easily specify per-environment values rather than hard-coding the value into the AlbumtArtService class. With that Configuration code in place, the hard-coded value may be removed form the AlbumArtService class. The property still needs to be declared as a field in the class but should not be assigned a value. The framework will take care of initialising the property with the value specified in Config.groovy

In Grails 2 I have defined properties of a service bean as described above.

Now in Grails 3 I am trying to define service properties in my application.ml file:

environments:
    development:
        beans:
            transactionalMailService:
                mandrillApiKey: XAPIKEYVALUEX
            shareWithShoptimixUseCaseService:
                appStore: https://itunes/myapp
        grails:
            serverURL: http://localhost:8080
        dataSource:
            driverClassName: org.postgresql.Driver
            dialect: org.hibernate.dialect.PostgreSQL9Dial

    ....
    ...
    ..
    .

Then in my service:

class TransactionalMailService {

    def mandrillApiKey

    ....
    ...
    ..
    .
}

The property is not being set though. Any idea how to do this in Grails 3?

2

There are 2 best solutions below

0
On

I have a solution, but to me it's still a work-around.

I like the way controller and service bean properties can be set in Grails 2. But being unable to get it to work the same way in Grails 3, I chose to go with setting the properties in Bootstrap.groovy

def init = { servletContext ->
        myService.someProperty = 'some value'
...
}

I don't consider this the answer, but it does work.

0
On

You need to put multiple documents into the same YML file.

beans:
   transactionMailService:
      mandrilApiKey: real key
---
spring:
    profiles: development
beans:
      transactionMailService:
        mandrilApiKey: dev key

this is (I think) because beans are configured by spring