How to Dynamically Load Groovy Beans into Spring at Runtime

This article explains how to use Spring to hot‑load Groovy scripts stored in a database as beans, enabling on‑the‑fly data source access, RPC calls, and dependency injection without restarting the Java application.

Programmer DD
Programmer DD
Programmer DD
How to Dynamically Load Groovy Beans into Spring at Runtime

In a data‑analysis project that requires rapid feature rollout, the author uses Java together with Groovy because Groovy scripts support hot‑loading. Simple analysis tasks such as statistics, sorting, and filtering are placed in Groovy, and new scripts can be added and loaded into the JVM instantly.

The goal is to also move data‑source access and preprocessing into Groovy scripts, allowing new product features to be deployed by updating scripts stored in the database while the system remains stable.

Solution

The chosen approach (Plan B) is to let Groovy scripts have the ability to access data sources, invoke RPC services, etc., and to manage these scripts with Spring.

PlanA: Java + hot‑load

PlanB: Groovy + hot‑load

Implementation steps:

Store Groovy scripts in the database. A scheduled task polls the database for updates, reads the script content, and parses it into a Class using GroovyClassLoader.

Use Spring’s BeanDefinitionBuilder to create a BeanDefinition that contains the script’s meta‑information and dependencies.

Register the BeanDefinition in the ApplicationContext and let Spring perform dependency injection.

Retrieve the bean from the context with context.getBean("hello") and invoke its methods.

Below is a simplified Groovy script ( Hello.groovy) stored in the database:

import org.springframework.beans.factory.annotation.Autowired

class Hello {
    @Autowired
    HelloService service

    HelloService getService() {
        return service
    }

    def run() {
        print(service.hello())
    }
}

The accompanying Java service ( HelloService.java) provides a simple method that could be replaced with real data‑source logic:

import org.springframework.stereotype.Component;

@Component
public class HelloService {
    public String hello() {
        return "now hello";
    }
}

Key code snippets for the dynamic registration process:

// Obtain Spring ApplicationContext (e.g., via ApplicationContextAware)
String scriptContent = "..."; // fetched from DB
Class clazz = new GroovyClassLoader().parseClass(scriptContent);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
BeanDefinition beanDef = builder.getRawBeanDefinition();
context.getAutowireCapableBeanFactory().applyBeanPostProcessorsAfterInitialization(beanDef, "hello");
beanFactory.registerBeanDefinition("hello", beanDef);
Hello hello = (Hello) context.getBean("hello");
hello.run(); // prints "now hello"

Note: In a production setting, additional concerns such as service degradation, security controls, and error handling must be addressed.

Reference materials include articles on Groovy‑enhanced Spring, dynamic bean injection, and Spring bean registration techniques.

Diagram
Diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaDynamic LoadingGroovyBean Registration
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.