XML Rule Definitions
rulii-spring 1.2.0 introduces an XML namespace that lets you declare rules, rulesets, and validation rules entirely in XML files. This is useful when business logic needs to live outside of compiled code — in configuration files that non-developers can edit and deploy without recompiling.
Namespace Declaration
Section titled “Namespace Declaration”Add the rulii namespace to your Spring XML context file:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:r="http://www.rulii.org/schema/rulii" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.rulii.org/schema/rulii classpath:org/rulii/spring/xml/rulii-spring.xsd">
<!-- rules go here -->
</beans>Setting the Default Language
Section titled “Setting the Default Language”All expression elements — given, then, otherwise, pre-condition, initializer, stop-condition, finalizer — are evaluated by a script engine. The default language is "el" (SpEL) when none is configured. Use <r:scripting> to change the file-wide default:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:r="http://www.rulii.org/schema/rulii" ...>
<!-- Use SpEL (the default) -- expressions reference bindings via #ctx --> <r:scripting defaultLanguage="el"/>
<r:rule name="PremiumOrderRule"> <given>#ctx.orderTotal >= 500</given> <then>#ctx.discountTier = 'PREMIUM'</then> </r:rule>
</beans>Place <r:scripting> once near the top of the file, before any <r:rule> or <r:ruleset> elements — the setting applies to every expression element that follows it. Any individual element can still override the language with a language attribute:
<!-- File default is SpEL, but this one condition uses GraalJS --><r:scripting defaultLanguage="el"/>
<r:rule name="RegexRule"> <given language="js">/^[A-Z]{3}-\d{4}$/.test(ctx.productCode)</given> <then>#ctx.validated = true</then></r:rule>Declaring a Rule
Section titled “Declaring a Rule”Use <r:rule> to define a rule with a condition (pre-condition, given), actions (then, otherwise), all expressed as SpEL:
<r:rule name="AgeVerificationRule"> <given>#ctx.age >= 18</given> <then>#ctx.status = 'approved'</then> <otherwise>#ctx.status = 'denied'</otherwise></r:rule>Declaring a RuleSet
Section titled “Declaring a RuleSet”<r:ruleset> supports typed parameters, lifecycle hooks, an inline rule collection, and both built-in and custom validation rules:
<r:ruleset name="RegistrationValidation">
<r:param name="name" type="java.lang.String"/> <r:param name="email" type="java.lang.String"/> <r:param name="age" type="java.lang.Integer"> <r:default-value>0</r:default-value> </r:param>
<r:rules> <r:notNull binding="name" errorCode="NAME_REQUIRED"/> <r:notBlank binding="name" errorCode="NAME_BLANK"/> <r:size binding="name" min="2" max="50"/> <r:email binding="email" errorCode="EMAIL_INVALID"/> <r:min binding="age" min="18" errorCode="UNDERAGE"/> </r:rules>
</r:ruleset>Result Type (new in 2.2.0)
Section titled “Result Type (new in 2.2.0)”rulii 2.2 records a formal result type in a ruleset’s definition (RuleSetDefinition.getResolvedResultType()), derived from the result extractor when the author does not state it. A script extractor cannot declare its return type, so the XML namespace lets you state it — either type on <result-extractor> or result-type on <r:ruleset>:
<r:ruleset name="PricingRules"> <result-extractor type="java.math.BigDecimal">#ctx.totalPrice</result-extractor> ...</r:ruleset>
<!-- or, equivalently, on the parent element --><r:ruleset name="PricingRules" result-type="java.math.BigDecimal"> <result-extractor>#ctx.totalPrice</result-extractor> ...</r:ruleset>- One or the other — declaring both is a parse error reported with the XML location.
- The name is loaded through the context class loader; an unknown class fails the bean with an
UnrulyExceptionnaming the ruleset. - Existing XML is unchanged: a ruleset without an extractor reports
RuleSetExecutionStatus, a script extractor without a stated type reports its type as unknown. - Programmatically,
RuleSetFactoryBean.setResultTypeName(String)does the same.
Lifecycle Hooks
Section titled “Lifecycle Hooks”RuleSets support four lifecycle hooks, each taking a SpEL expression:
<r:ruleset name="PricingRules"> <pre-condition>#ctx.enabled == true</pre-condition> <initializer>#ctx.discount = 0</initializer> <stop-condition>#ctx.discount >= #ctx.maxDiscount</stop-condition> <finalizer>#ctx.totalPrice = #ctx.basePrice - #ctx.discount</finalizer>
<r:rules> <r:rule name="LoyaltyDiscount"> <given>#ctx.loyaltyYears >= 5</given> <then>#ctx.discount = #ctx.discount + 10</then> </r:rule> </r:rules></r:ruleset>Inline Attribute Shorthand
Section titled “Inline Attribute Shorthand”Every condition and action child element also has a terse attribute form, so simple rules can be declared on a single element. The AgeVerificationRule from above, written inline:
<r:rule name="AgeVerificationRule" given="#ctx.age >= 18" then="#ctx.status = 'approved'" otherwise="#ctx.status = 'denied'"/>
<!-- pre-condition is available inline as well --><r:rule name="VipUpgradeRule" pre-condition="#ctx.customer != null" given="#ctx.customer.lifetimeSpend >= 10000" then="#ctx.customer.tier = 'VIP'"/>Custom validation rules support an inline given attribute:
<r:validationRule name="FutureShipDate" errorCode="ORD-003" errorMessage="Shipping date must not be in the past" given="#ctx.shipDate != null and !#ctx.shipDate.isBefore(T(java.time.LocalDate).now())"/>RuleSets accept all four lifecycle hooks as attributes — pre-condition, initializer, stop-condition, and finalizer. The PricingRules example, condensed:
<r:ruleset name="PricingRules" pre-condition="#ctx.enabled == true" initializer="#ctx.discount = 0" stop-condition="#ctx.discount >= #ctx.maxDiscount" finalizer="#ctx.totalPrice = #ctx.basePrice - #ctx.discount"> <r:rules> <r:rule name="LoyaltyDiscount" given="#ctx.loyaltyYears >= 5" then="#ctx.discount = #ctx.discount + 10"/> </r:rules></r:ruleset>RuleFlows follow the same pattern: finalizer and returning are available as attributes on <r:ruleflow>, and flow commands offer inline forms too — condition on <r:when>, source and stop-condition on <r:for-each>, and expr on <r:apply> / <r:execute> / <r:bind>. See XML RuleFlows for the full command grammar.
<r:ruleflow name="CheckoutFlow" finalizer="#ctx.audited = true" returning="#ctx.totalPrice"> <r:run name="PricingRules"/> <r:when condition="#ctx.totalPrice >= 100"> <r:then> <r:execute expr="#ctx.freeShipping = true"/> </r:then> </r:when></r:ruleflow>Referencing Existing Beans or Classes
Section titled “Referencing Existing Beans or Classes”You can include existing Spring beans or annotated rule classes inside a ruleset’s rule collection:
<r:rules> <!-- Reference an existing Spring bean --> <r:bean-ref name="myEligibilityRule"/>
<!-- Reference an annotated @Rule class --> <r:class-ref class="com.example.rules.AgeVerificationRule"/></r:rules>Predefined Validation Rule Elements
Section titled “Predefined Validation Rule Elements”All 48 built-in validators are available as first-class XML elements. Up to 2.2.0 there were 37; rulii-spring 2.3.0 adds the eleven validators that came with rulii 2.2.0: uuid, isbn, ean, luhnCheck, mod10Check, mod11Check, uniqueElements, normalized, codePointLength, durationMin and durationMax. Every element accepts binding (required), errorCode, severity, and errorMessage. Error messages support Spring property placeholder substitution:
<r:notNull binding="name" errorMessage="${validation.name.required}"/><r:notBlank binding="name"/><r:size binding="name" min="2" max="100"/><r:email binding="email"/><r:pattern binding="phone" pattern="^\+?[0-9]{7,15}$"/><r:min binding="age" min="18"/><r:max binding="quantity" max="999"/><r:future binding="appointmentDate"/><r:positive binding="price" severity="FATAL"/><r:in binding="status" values="PENDING,ACTIVE,CLOSED"/><r:startsWith binding="code" values="PRD-,SKU-"/>Validator Settings as Attributes (new in 2.3.0)
Section titled “Validator Settings as Attributes (new in 2.3.0)”Every setting a validator’s builder has in Java is an optional attribute of its element, under the builder method’s name. A setting left out keeps the Java default, so existing XML is unaffected. Up to 2.2.0 only caseSensitive on pattern was available.
<r:isbn binding="isbn" type="ANY"/><r:uuid binding="orderId" versions="4" letterCase="INSENSITIVE"/><r:durationMax binding="session" max="PT8H" inclusive="false"/><r:url binding="site" protocol="https" host="${site.host}"/><r:pattern binding="notes" pattern="a.b" flags="DOTALL,CASE_INSENSITIVE"/><r:size binding="tags" min="1" max="3" failOnNull="false"/>| Elements | Settings |
|---|---|
alpha, alphaNumeric, decimal, numeric |
allowSpace |
decimalMin, decimalMax, durationMin, durationMax |
inclusive |
email |
allowLocal, allowTopLevelDomain, anyDomain, pattern, flags |
url |
protocol, host, port, regexp, flags |
pattern |
caseSensitive, flags |
normalized |
form |
codePointLength |
normalization |
uuid |
allowEmpty, allowNil, versions, variants, letterCase |
luhnCheck, mod10Check, mod11Check |
startIndex, endIndex, checkDigitIndex, ignoreNonDigitCharacters |
mod10Check |
multiplier, weight |
mod11Check |
threshold, treatCheck10As, treatCheck11As, processingDirection |
ean, isbn |
type |
| every element | failOnNull, valueName |
- A switch without an argument in Java (
allowSpace()) is a boolean. - An enum setting takes the Java constant names, checked by the schema.
versionsandvariantsare comma-separated numbers.flagsis a comma-separated list ofjava.util.regex.Patternflag names (flags="MULTILINE,DOTALL").durationMinanddurationMaxtake an ISO-8601 duration, asjava.time.Duration.parsereads it (PT30M,PT8H,P2D).failOnNull="false"skips the rule for a null value;notNull,notBlankandnotEmptyaccepttrueonly, as in Java.- Text and number settings accept
${...}properties. A value that cannot be converted fails at startup, naming the rule and the attribute. - Not available in XML:
param(name, value)andparams(map), the extra violation parameters.
Custom Scripted Validation Rules
Section titled “Custom Scripted Validation Rules”When the predefined validators don’t cover a business case, <r:validationRule> lets you write the condition as a script expression. The rule registers a RuleViolation when the <given> condition returns false:
<r:validationRule name="ValidShippingDate" errorCode="SHIPPING_DATE_INVALID" severity="ERROR" errorMessage="Shipping date must be today or in the future"> <given>#ctx.shippingDate != null and !#ctx.shippingDate.isBefore(T(java.time.LocalDate).now())</given></r:validationRule>Supported attributes:
| Attribute | Required | Description |
|---|---|---|
| name | Yes | Unique rule identifier, also used as the Spring bean name |
| errorCode | Yes | Code placed in the RuleViolation when the condition fails |
| severity | No | ERROR (default), FATAL, WARNING, INFO |
| errorMessage | No | Message template shown in the violation (supports ${...} placeholders) |
| defaultMessage | No | Fallback message when the template cannot be resolved via MessageResolver |
| description | No | Human-readable documentation for the rule |
The <given> child element supports the same language attribute as any other expression element, letting you mix languages within the same file. Custom validation rules can also be placed directly inside a <r:ruleset>:
<r:ruleset name="OrderValidation" validating="true">
<r:param name="productCode" type="java.lang.String"/> <r:param name="quantity" type="java.lang.Integer"/> <r:param name="shipDate" type="java.time.LocalDate"/>
<r:rules> <!-- Predefined rules --> <r:notBlank binding="productCode" errorCode="ORD-001"/> <r:min binding="quantity" errorCode="ORD-002" min="1"/>
<!-- Custom scripted validation rule --> <r:validationRule name="FutureShipDate" errorCode="ORD-003" errorMessage="Shipping date must not be in the past"> <given>#ctx.shipDate != null and !#ctx.shipDate.isBefore(T(java.time.LocalDate).now())</given> </r:validationRule> </r:rules>
</r:ruleset>Category & Tags (new in 2.1.0)
Section titled “Category & Tags (new in 2.1.0)”Every artifact element — <r:rule>, <r:validationRule>, the predefined validators, <r:ruleset>, <r:ruleflow>, and inline rules — takes a category attribute (at most one, with / between the levels of a hierarchy, e.g. Pricing/Discounts) and a comma-separated tags attribute. They reach rulii 2.1’s Categorized.getCategory() and getTags() on the rule, ruleset, and ruleflow definitions. Both are purely descriptive — rulii never reads them at execution time — and exist for tools that group and filter, such as rulii-explorer.
A file-level <r:defaults category="..." tags="..."/> applies to every artifact in the file, like <r:scripting>: an element’s category replaces the file default, while its tags are added to the default’s.
<r:defaults category="Pricing" tags="pricing"/>
<r:rule name="LoyaltyDiscount" category="Pricing/Discounts" tags="vip, discount" given="#ctx.loyaltyYears >= 5" then="#ctx.discount = #ctx.discount + 10"/>
<!-- category: Pricing/Discounts (replaces the file default) --><!-- tags: pricing, vip, discount (element tags add to the default's) -->Two more introspection touches land in 2.1.0: the description attribute on <r:param> is carried through to InputParameter.description() on rulesets and ruleflows, and every XML-declared artifact records the file and line it was declared at as its SourceDefinition — see XML File & Line Provenance.
Loading XML Files via @RuleScan
Section titled “Loading XML Files via @RuleScan”Use the xmlLocations attribute on @RuleScan to tell rulii-spring where to find your XML rule files. All *.xml files found inside each folder are loaded automatically. See Rule Scanning & Discovery for the full details.
@SpringBootApplication@RuleScan( scanBasePackages = "com.example.rules", xmlLocations = { "classpath:rules/pricing/", "classpath:rules/validation/" })public class MyApp { }