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

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
O
OpenAI News
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Webroot Blog
Webroot Blog
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
N
News | PayPal Newsroom
H
Hacker News: Front Page
博客园_首页
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Last Watchdog
The Last Watchdog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Schneier on Security
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Y
Y Combinator Blog
Cyberwarzone
Cyberwarzone
Microsoft Security Blog
Microsoft Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
GbyAI
GbyAI
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog
M
MIT News - Artificial intelligence
G
GRAHAM CLULEY
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
Last Week in AI
Last Week in AI
T
Troy Hunt's Blog
L
Lohrmann on Cybersecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
量子位
博客园 - 聂微东
S
Securelist
博客园 - 三生石上(FineUI控件)
F
Full Disclosure
G
Google Developers Blog
L
LINUX DO - 热门话题
P
Proofpoint News Feed
AI
AI
PCI Perspectives
PCI Perspectives

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building Rule-Validator: Why I Built a Java Annotation-Based Rule Engine After 3 Years of Fighting Business Rules
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!