Overriding an Injected Bean in Grails 3.x

In this article we will see how can we override a plugin class’s methods by overriding a registered bean in our Grails application.
The following steps illustrate how to achieve this- 

The first step is to create an interface in our plugin under src/main/groovy/ directory. This interface would represent a class that would contain it’s method definitions. Let’s say we created an interface named DummyService. This interface should contain the necessary method declarations that you wish to override in your installing application.

Now create a class in src/main/groovy directory in your plugin which implements the DummyService interface. Let’s say our class is DefaultService. Now here we can provide the default method definitions for our plugin use.

Next step is to register DefaultService class’s bean. In our plugin, we can register this bean in doWithSpring closure in following way –

Closure doWithSpring() { ->
    // Injecting bean for DefaultService class
    dummyService(DefaultService)
}

This step would register DefaultService class’s bean as dummyService.

Now we move to our installing app. In our installing application, the first step is to create a class in src/main/groovy directory. Let’s say we created CustomService class. This class should implement DummyService class from our plugin in order to override the methods defined in DefaultService class. This can be done by overriding DefaultService class’s bean for CustomService class.

Now to override this bean in our installing application we will use grails-app/conf/spring/resources.groovy file.

beans = {
    // Overriding dummyService bean and injecting it for CustomService class.
    dummyService(CustomService)
}

This would override dummyService bean in your installing application.

Follow this link to our github repository which shows a demo implementation.

Link to plugin
Link to application

About CauseCode: We are a technology company specializing in Healthtech related Web and Mobile application development. We collaborate with passionate companies looking to change health and wellness tech for good. If you are a startup, enterprise or generally interested in digital health, we would love to hear from you! Let's connect at bootstrap@causecode.com

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY UPDATED!

Do you want to get articles like these in your inbox?

Email *

Interested groups *
Healthtech
Business
Technical articles

Archives