Martini Custom Functions
Martini allows the creation of custom Groovy extension modules. These modules enable developers to add new methods to existing classes, including JDK classes, enhancing functionality without altering original class definitions.
Understanding Groovy's Extension Module
Groovy includes a default extension module that adds methods to JDK classes. For example, the sum()
method, not a native part of the ArrayList
class, is available through Groovy's extension.
Leveraging Martini's Extension Modules
Martini offers additional extension modules with utility methods to expedite application development. These modules provide convenient, one-line solutions for common programming tasks.
Developing Custom Extension Modules
Procedure
-
Create a New Project:
- Begin by establishing a new project environment.
- Develop a class (or classes) for your extension methods, ensuring they are
public
andstatic
. The first parameter of each method should be the type of the class you intend to extend.
-
Crafting Extension Methods:
- Your methods should directly address the functionalities you wish to add or enhance.
- Example:
1 2 3 4 5
class CustomExtensions { static enhancedMethod(ExistingClass instance, ...) { // Implementation logic } }
-
Descriptor File Creation:
- In your project's
META-INF/services
directory, create a descriptor file namedorg.codehaus.groovy.runtime.ExtensionModule
. - Detail your module with properties like
moduleName
,moduleVersion
, andextensionClasses
.
- In your project's
-
Packaging and Deployment:
- Package your classes and descriptor file into a JAR.
- Place the JAR in your Martini package's
lib
directory.
Utilizing Custom Functions
- Deployed functions are accessible within your Martini services.
- Usage example:
1 2
ExistingClass instance = new ExistingClass(...) instance.enhancedMethod(...)
Best Practices
- Keep static and instance methods in separate classes.
- Organize different functionalities into distinct modules.
Extension Module Portability
Custom modules can be shared between Martini and other projects, provided there are no Martini-specific class dependencies.