Drools不同DRL文件复用类型与全局变量?版本7.6.0可升级
Hey there, let's tackle this "Unable to resolve ObjectType" issue you're hitting when trying to reuse types and globals from common.drl in app.drl. I've dealt with similar headaches in Drools before, so here are the key fixes to try out:
1. Ensure Correct DRL Loading Order
Drools processes files in the order they're added to the KieBase. If app.drl loads before common.drl, it won't recognize the types or globals defined in the core library.
- Code-based setup: Add
common.drlfirst when building your KieFileSystem:KieFileSystem kfs = kieServices.newKieFileSystem(); // Add common.drl BEFORE app.drl kfs.write("src/main/resources/common.drl", commonDrlContent); kfs.write("src/main/resources/app.drl", appDrlContent); // Proceed to build KieContainer/KieBase - kmodule.xml setup: Explicitly define dependencies to enforce loading order, or group both files under the same package path.
2. Use Proper Packages & Imports
If common.drl uses a specific package, app.drl needs to either:
- Share the same package declaration, or
- Import the types from
common.drl's package.
Example:
common.drl:
package com.yourteam.rules.core; declare Customer id: Long name: String tier: String end global java.util.Map<String, Integer> tierDiscounts;
app.drl:
package com.yourteam.rules.app; // Import the Customer type from core package import com.yourteam.rules.core.Customer; // No need to re-declare the global - reference it directly rule "Apply Tier Discount" when c: Customer(tier == "PREMIUM") then Integer discount = tierDiscounts.get("PREMIUM"); // Add your rule logic here end
3. Avoid Conflicting Type Declarations
Double-check that you haven't accidentally re-declared the same type in both files. Even a tiny difference (like a missing field) will make Drools treat them as separate types, triggering resolution errors.
- If you need to extend a core type, use
extendinstead of re-declaring:declare PremiumCustomer extends com.yourteam.rules.core.Customer loyaltyPoints: Integer end
4. Verify KieBase Configuration
Make sure both DRL files are part of the same KieBase. If you create separate KieBases for each file, they'll have isolated type spaces and can't share definitions.
- For
kmodule.xml, include both files in the same kbase:<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> <kbase name="mainKbase" packages="com.yourteam.rules.*"> <ksession name="mainKsession"/> </kbase> </kmodule>
5. Upgrade Drools (If Possible)
Drools 7.6.0 is quite old (released in 2018). Newer 7.x LTS versions or 8.x have improved type resolution and error reporting, which might fix edge cases causing your issue. Just review the migration guide first to avoid breaking changes.
After applying these steps, rebuild your KieContainer and test again. Most often, this error comes down to app.drl not having access to common.drl's definitions due to loading order, missing imports, or isolated type spaces.
内容的提问来源于stack exchange,提问作者marinier

