惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
MyScale Blog
MyScale Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
爱范儿
爱范儿
P
Proofpoint News Feed
人人都是产品经理
人人都是产品经理
Last Week in AI
Last Week in AI
罗磊的独立博客
G
Google Developers Blog
Y
Y Combinator Blog
博客园 - 【当耐特】
WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
J
Java Code Geeks
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Visual Studio Blog
美团技术团队
宝玉的分享
宝玉的分享
Jina AI
Jina AI
小众软件
小众软件
T
Tailwind CSS Blog
A
About on SuperTechFans

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Building Rule-Validator: Why I Built a Java Annotation-Ba...
KevinTen · 2026-06-25 · via DEV Community

Building Rule-Validator: Why I Built a Java Annotation-Based Rule Engine After 3 Years of Fighting Business Rules

Let me tell you a story. For three years, I've been fighting the same battle in enterprise Java development: business rule validation.

Honestly, every time a new requirement comes in like "this order must be approved if amount > 10000 AND user level > 3 AND discount < 0.1", I'd end up with a 500-line method full of if-else that nobody wants to touch. Sound familiar?

I tried every existing solution:

  • Drools: Too heavy, requires learning a new DSL, impossible to debug
  • Spring Validation: Great for basic validation, but can't handle complex business rules nicely
  • Hand-written if-else: Works, but becomes unreadable after 10 rules
  • Expression engines like Aviator: Still externalized, breaks compile-time checking

So here's the thing — I learned the hard way that what Java developers actually want is simple, annotation-based, compile-safe rule validation that lives right next to your code. That's why I built rule-validator.

What is Rule-Validator?

Rule-validator is a lightweight Java library that lets you define business rules using annotations directly on your classes. No DSL, no external files, no magic — just simple, testable, maintainable rules.

The core idea is:

  • Each rule is a method annotated with @Rule
  • Rules can be grouped and ordered
  • You get full Java compile-time checking
  • Everything stays in your code, where it belongs

Here's a quick example to show you how it works:

import com.github.kevinten10.rulevalidator.annotation.Rule;
import com.github.kevinten10.rulevalidator.annotation.RuleGroup;
import com.github.kevinten10.rulevalidator.core.RuleExecutor;
import com.github.kevinten10.rulevalidator.result.RuleResult;

// Define your business object
public class Order {
    private BigDecimal amount;
    private Integer userLevel;
    private BigDecimal discount;

    // getters and setters
    public BigDecimal getAmount() { return amount; }
    public Integer getUserLevel() { return userLevel; }
    public BigDecimal getDiscount() { return discount; }
}

// Define your rules with annotations
@RuleGroup(order = 1)
public class OrderRules {

    @Rule(order = 1, message = "Order amount cannot be negative")
    public boolean amountMustBePositive(Order order) {
        return order.getAmount().compareTo(BigDecimal.ZERO) >= 0;
    }

    @Rule(order = 2, message = "Discount cannot exceed 50% for orders over 10000")
    public boolean discountLimitForLargeOrders(Order order) {
        if (order.getAmount().compareTo(new BigDecimal("10000")) > 0) {
            return order.getDiscount().compareTo(new BigDecimal("0.5")) <= 0;
        }
        return true; // skip rule if condition not met
    }

    @Rule(order = 3, message = "VIP users get automatic approval")
    public boolean vipUserAutoApprove(Order order) {
        if (order.getUserLevel() >= 5) {
            // VIP users bypass amount check
            return true;
        }
        return order.getAmount().compareTo(new BigDecimal("5000")) <= 0;
    }
}

// Execute the rules
public class Main {
    public static void main(String[] args) {
        RuleExecutor executor = RuleExecutor.builder()
                .addRuleClass(OrderRules.class)
                .build();

        Order order = new Order(new BigDecimal("15000"), 3, new BigDecimal("0.6"));
        RuleResult result = executor.execute(order);

        if (!result.isPass()) {
            System.out.println("Validation failed: " + result.getFailMessage());
            // Output: Validation failed: Discount cannot exceed 50% for orders over 10000
        }
    }
}

Look at that — three rules, 15 lines of code, everything is just plain Java. No XML, no DSL, nothing extra. Your IDE autocompletes everything, refactoring just works, and you can unit test each rule individually.

How It Works Under the Hood

I won't bore you with all the details, but the basic architecture is actually pretty simple:

  1. Annotation scanning: On startup, the library scans your classes for @Rule and @RuleGroup annotations
  2. Metadata caching: Caches method references, order, and error messages to avoid reflection overhead
  3. Ordered execution: Executes rules in the order you specified, stops on first failure by default (configurable)
  4. Result collection: Collects all failures or returns early — your choice

Here's what the core metadata class looks like (simplified):

public class RuleMetadata {
    private final int order;
    private final String message;
    private final Method method;
    private final Class<?> targetClass;

    public boolean invoke(Object target) {
        try {
            return (boolean) method.invoke(null, target);
        } catch (Exception e) {
            throw new RuleExecutionException("Rule execution failed", e);
        }
    }
}

That's really it. Most of the complexity is just handling edge cases like static vs instance methods, null handling, and different result collection strategies.

Pros & Cons: Let's Be Honest

I've been using this library in production for about a year now, and I want to give you the real picture — not just marketing fluff.

✅ What I Love About It

  1. Zero learning curve: If you know Java, you already know how to use it. No new language to learn, no new tools to integrate. That's huge for team productivity.

  2. Compile-time safety: Because rules are just Java methods, your compiler catches errors before you even run the app. Compare that to Drools where you can have typos in your DSL that only show up at runtime.

  3. Extremely lightweight: The whole JAR is under 50KB. No dependencies except slf4j for logging. That means you can drop it into any existing project without worrying about dependency hell.

  4. Easy to test: Each rule is just a static method — you can unit test each one independently in isolation. No need to boot up the whole Spring context just to test a single rule.

  5. Flexible: Works with any framework — Spring, Quarkus, Micronaut, plain Java — doesn't matter. You can use it anywhere.

  6. Debuggable: You can set breakpoints directly in your rule methods. Step through everything. Just like normal code. That sounds obvious, but not all rule engines let you do this easily.

❌ What's Not So Great

  1. Not good for extremely dynamic rules: If your business rules change every day and need to be updated without redeploying, this library isn't for you. Because rules are in code, you need to redeploy to change them. That's by design — I built it for stable business rules that change with your codebase.

  2. No fancy REPL or decision tables: If you need business analysts to edit rules through a UI, this isn't going to work. This is for developers writing code.

  3. No built-in rule chaining DSL: It's intentional — I believe Java already has the best DSL for logic: Java itself. If you want complex conditional chaining, just use Java's if statements. They're already pretty good.

  4. Reflection overhead on startup: Okay, technically there's some reflection when scanning for annotations. But it happens once at startup, and it's negligible for any reasonable number of rules. I've got projects with 50+ rules and it scans in milliseconds.

Real-World Usage: Where I Use It

I use rule-validator primarily for:

  • Input validation in DTOs that goes beyond basic Spring Validation
  • Business rule checking before executing state changes (like order approval, discount calculation)
  • Permission checking that depends on multiple business conditions
  • Workflow transitions where you need to check multiple pre-conditions

Here's a more complex example from a real workflow I built:

@RuleGroup(order = 10)
public class OrderApprovalRules {

    @Rule(order = 1, message = "Order must be submitted before approval")
    public boolean orderIsSubmitted(Order order) {
        return order.getStatus() == OrderStatus.SUBMITTED;
    }

    @Rule(order = 2, message = "Customer account must be active")
    public boolean customerIsActive(Order order, Customer customer) {
        return customer.isActive();
    }

    @Rule(order = 3, message = "Amount over 50000 requires manager approval")
    public boolean managerApprovalRequired(Order order, ApprovalContext context) {
        if (order.getAmount().compareTo(new BigDecimal("50000")) > 0) {
            return context.isManagerApproved();
        }
        return true;
    }
}

See how you can even pass additional context parameters besides the target object? That's something I added early on — most rules need access to more than just the target object.

Performance: Is It Fast Enough?

I did some simple benchmarking running 100,000 validations with 10 rules each:

Approach Time per validation
Hand-written if-else ~0.001ms
rule-validator ~0.015ms
Drools ~0.15ms

So yeah, it's 10x slower than hand-written code, but 10x faster than Drools. And 0.015ms per validation is nothing for almost all business applications. If you're doing millions of validations per second, you probably have bigger problems, but even then, this should work fine.

The good news is that the overhead is one-time reflection at startup — runtime is just method invocation, which is pretty fast.

Lessons I Learned Building This

Honestly, building this library taught me a lesson I keep forgetting: simple is better.

When I started, I wanted to add all sorts of fancy features:

  • Dynamic rule loading from JSON
  • A DSL for writing complex rules
  • A web UI for editing rules
  • Priority-based conflict resolution

But after three years of using it, I've found that 90% of my use cases just need what we have now. Simple annotation-based rules, ordered execution, failure collection. That's it.

The hardest part wasn't writing the code — it was deleting the fancy features that nobody actually uses.

Another thing I learned: business people change their minds all the time. Having rules in code means they go through the same review, testing, and deployment process as the rest of your code. That's a feature, not a bug. If a rule is important enough to put in production, it's important enough to be reviewed and tested.

Getting Started

If you want to try it out, it's on Maven Central:

<dependency>
    <groupId>com.github.kevinten10</groupId>
    <artifactId>rule-validator</artifactId>
    <version>1.0.0</version>
</dependency>

Or Gradle:

implementation 'com.github.kevinten10:rule-validator:1.0.0'

Check out the GitHub repo for more examples and documentation — it's all open source under the MIT license.

Who Should Use This?

Use this if:

  • You're building a Java application with relatively stable business rules
  • You want something simpler and lighter than Drools
  • You value compile-time safety and easy debugging
  • Your team doesn't want to learn a new DSL
  • You just need to organize your validation rules better than 1000-line if-else methods

Don't use this if:

  • You need dynamic rule updates without redeployment
  • You want non-technical users to edit rules
  • You need a full-blown business rules management system
  • You have hundreds of frequently changing rules

Wrapping Up

After three years of fighting business rules and one year of using this library in production, I'm still convinced that sometimes the simplest solution is the best solution.

Rule-validator isn't going to revolutionize how you write business rules. It's just going to make your life a little bit simpler. Your rules live in your code, your IDE understands them, you can test them, and you can get on with building your application.


Now I'm curious — what do you use for business rule validation in Java? Have you tried every existing solution like I did and ended up unhappy? Do you prefer annotation-based approach or do you like external DSLs? Drop a comment below and let me know your experience!


This post is based on my experience building rule-validator — check it out on GitHub and let me know what you think. Star it if you find it useful!