drools5入门(1)

安装drools5插件

 

直接解压drools-5.0-eclipse-all.zipeclipse下的 dropins目录中。

 

建立一个Java Project

 

引入drools必备的jar

 

antlr-runtime-3.1.1.jar

core-3.4.2.v_883_R34x.jar

drools-api-5.0.1.jar

drools-compiler-5.0.1.jar

drools-core-5.0.1.jar

mvel2-2.0.10.jar

 

创建一个UserPOJO类:

package com.test;

 

publicclass User {

  

   private String loginName;

 

   public String getLoginName() {

      returnloginName;

   }

 

   publicvoid setLoginName(String loginName) {

      this.loginName = loginName;

   }

 

   @Override

   publicint hashCode() {

      finalint prime = 31;

      int result = 1;

      result = prime * result

           + ((loginName == null) ? 0 : loginName.hashCode());

      return result;

   }

 

   @Override

   publicboolean equals(Object obj) {

      if (this == obj)

        returntrue;

      if (obj == null)

        returnfalse;

      if (getClass() != obj.getClass())

        returnfalse;

      User other = (User) obj;

      if (loginName == null) {

        if (other.loginName != null)

           returnfalse;

      } elseif (!loginName.equals(other.loginName))

        returnfalse;

      returntrue;

   }

 

   @Override

   public String toString() {

      return"User [loginName=" + loginName + "]";

   }

}

 

 

新建一个规则定义文件

package com.test;

 

rule"rule_01"

   when

      $user : User(loginName != null)

   then

      System.out.println("hello, " + $user.getLoginName());

end

 

最后写一个RuleApp规则启动类:

package com.test;

 

import org.drools.KnowledgeBase;

import org.drools.KnowledgeBaseFactory;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderFactory;

import org.drools.builder.ResourceType;

import org.drools.io.ResourceFactory;

import org.drools.runtime.StatefulKnowledgeSession;

 

publicclass RuleApp {

 

   publicstaticvoid main(String[] args) {

      KnowledgeBase knowledgeBase = createKnowledgeBase();

      StatefulKnowledgeSession session = knowledgeBase

           .newStatefulKnowledgeSession();

      try {

        User user = new User();

        user.setLoginName("zhangsan");

        session.insert(user);

        session.fireAllRules();

      } finally {

        session.dispose();

      }

   }

 

   privatestatic KnowledgeBase createKnowledgeBase() {

      KnowledgeBuilder builder = KnowledgeBuilderFactory

           .newKnowledgeBuilder();

      builder.add(ResourceFactory.newClassPathResource("helloworld.drl",

           User.class), ResourceType.DRL);

      if (builder.hasErrors()) {

        thrownew RuntimeException(builder.getErrors().toString());

      }

      KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();

      knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());

      return knowledgeBase;

   }

 

}

 

 

测试输出

hello, zhangsan

 

 

 

 

你可能感兴趣的:(drools)