zoukankan      html  css  js  c++  java
  • 在JBPM的Handle类中调用Spring管理的类

    我们在使用JBPM定义流程的时候经常要在流程定义文件中加入一个继承xxxHandler的类来实现我们的业务逻辑判断或者其他的需求,在这个类中一般都是用Spring的Application来获取,而这种情况每次都需要加载配置。

          假设使用的Handle类是RoleAssignmentHandler,需要注入的属性石UserService, 以下有几种解决办法:

    1、在RoleAssignmentHandler中把UserService声明成static

    Java代码  收藏代码
    1. //@Component  
    2. public class RoleAssignmentHandler implements AssignmentHandler {  
    3.   
    4.     private static final long serialVersionUID = 1L;  
    5.   
    6.         //(注解式的Resource不能用在static修饰的字段)  
    7.     //@Resource(name="userService")//配置static的userService  
    8.     private static UserService userService;  
    9.   
    10.     public void assign(Assignable arg0, OpenExecution arg1) throws Exception {  
    11.   
    12.         userService.getUserById("");//调用userService的方法  
    13.     }          
    14.   
    15.          public void setUserService(UserService userService) {  
    16.   
    17.         RoleAssignmentHandler.userService = userService;  
    18.     }  
    19.   
    20. }  

        为什么定义成静态的就可以呢?我们都知道静态变量时类级别的变量,所有这个类的实例共享一份,那么第一次Spring给我们创建这个对象的时 候,userService有值了等到第二次JBPM给我们创建这个对象的时候由于UserService是static的,所以他依然会有值 所以通过这种方法我们可以得到UserService对象,但是我们并不推荐这种方法,因为确实有点浪费内存资源 Spring明明已经把这个对象创建好了但是我们却没有去使用这个对象而是去使用了另一个由JBPM给我们创建的一个对象,但这种方法是可行的。

    2、自动注入。

         首先定义一个类BeanAutowire实现BeanFactoryAware接口,并把这个类交给spring管理。

    Java代码  收藏代码
    1. @Component  
    2.   
    3.   
    4. public class BeanAutowire implements BeanFactoryAware{  
    5.   
    6.     private static  BeanFactory beanFactory;  
    7.   
    8.     public BeanAutowire() {  
    9.   
    10.         if (null != beanFactory) {  
    11.   
    12.             ((AutowireCapableBeanFactory)beanFactory).autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);  
    13.   
    14.         }  
    15.   
    16.     }  
    17.   
    18.     public void setBeanFactory(BeanFactory arg0) throws BeansException {  
    19.   
    20.         // TODO Auto-generated method stub  
    21.   
    22.         BeanAutowire.beanFactory=arg0;  
    23.   
    24.     }  
    25.   
    26. }  

       然后让RoleAssignmentHandler类继承BeanAutowire:

    Java代码  收藏代码
    1. public class RoleAssignmentHandler extends BeanAutowire implements AssignmentHandler {  
    2.   
    3.     private static final long serialVersionUID = 1L;  
    4.   
    5.     @Resource(name="userService")  
    6.   
    7.     private UserService userService;  
    8.   
    9.     public void assign(Assignable arg0, OpenExecution arg1) throws Exception {  
    10.   
    11.   
    12.         // TODO Auto-generated method stub  
    13.   
    14.   
    15.         userService.getUserById("");//调用userService的方法  
    16.   
    17.   
    18.     }  
    19.   
    20.          public void setUserService(UserService userService) {  
    21.   
    22.   
    23.         RoleAssignmentHandler.userService = userService;  
    24.   
    25.   
    26.     }  
    27. }  

        这样,在spring初始化的时候会把BeanFactory注入到BeanAutowire中去,在jbpm每次使用Handle类时候会new一个Handle的实例,这时候会首先调用父类的构造方法:

    Java代码  收藏代码
    1. public BeanAutowire() {  
    2.   
    3.         if (null != beanFactory) {  
    4.   
    5.             ((AutowireCapableBeanFactory)beanFactory).autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);  
    6.   
    7.         }  
    8.   
    9.     }  

        把需要注入的对象注入到Handle类的实例中去。

    3、参考springmodules.jar的方法

          我们先借鉴一下JbpmHandlerProxy这个类是怎么拿到Beanfactory对象的。我们要关联上源代码了解一下他的运行机制: 
    JbpmHandlerProxy的运行机制: 
    jbpmhandlerProxy通过一个JbpmFactoryLocator来得到一个Beanfactory对象,那么他是怎么得到的呢,jbpmfactoryLocator实现了一个BeanFactoryAwre接口,所以有个 
    setBeanfacotry(BeanFactory factory) 方法,那么是哪个类来调用的这个方法 呢?是LocalJbpmConfigurationFactoryBean他也实现了BeanFactoryAwre接口所以他也有一个 
    setBeanfacotry(BeanFactory factory) 方法,因为这个类的对象我们是让spring帮我们生成的,所以在tomcat启动的时候spring会把Beanfactory对象放作为参数传递给 
    LocalJbpmConfigurationFactoryBean实现的setBeanfacotry(BeanFactory factory) 中,然后再这个方法中LocalJbpmConfigurationFactoryBean又去调用jbpmfactoryLocator 
    类的setBeanfacotry(BeanFactory factory) 关键就在这里,JbpmFactoryLocator中有一个protected static BeanFactory defaultFactory = null; 他把setFactory方法传递给他的 
    Beanfactory对象赋值给了静态变量defaultFactory。 
    然后在JbpmHandlerProxy类的retrieveBeanFactory方法中new JbpmFaotoryLocator对象,因为他里面的Beanfactory属性是静态的所以不管你怎么new他都是有值的,然后返回这个值:

    Java代码  收藏代码
    1. protected BeanFactory retrieveBeanFactory() {    
    2.              BeanFactoryLocator factoryLocator = new JbpmFactoryLocator();    
    3.              BeanFactoryReference factory = factoryLocator.useBeanFactory(null);    
    4.              if (factory == null)    
    5.                  throw new IllegalArgumentException("no beanFactory found under key=" + null);    
    6.          
    7.              try {    
    8.                  return factory.getFactory();    
    9.              }    
    10.              finally {    
    11.                  factory.release();    
    12.              }    
    13.          }    

       以下是这个方法的具体实施办法:

    这里,由于springmodules跟jbpm4.4的集成有些问题,所以单独把JbpmFactoryLocator这个类拿了出来,修改一下相关类的引入就可以使用:

    Java代码  收藏代码
    1. /** 
    2.  * Created on Jan 24, 2006 
    3.  * 
    4.  * $Id: JbpmFactoryLocator.java,v 1.3 2006-12-06 14:13:18 costin Exp $ 
    5.  * $Revision: 1.3 $ 
    6.  */  
    7. package com.founder.jbpm.util;  
    8.   
    9. import java.util.ArrayList;  
    10. import java.util.HashMap;  
    11. import java.util.Iterator;  
    12. import java.util.List;  
    13. import java.util.Map;  
    14.   
    15. import org.apache.commons.logging.Log;  
    16. import org.apache.commons.logging.LogFactory;  
    17. import org.springframework.beans.BeansException;  
    18. import org.springframework.beans.FatalBeanException;  
    19. import org.springframework.beans.factory.BeanFactory;  
    20. import org.springframework.beans.factory.BeanFactoryAware;  
    21. import org.springframework.beans.factory.BeanNameAware;  
    22. import org.springframework.beans.factory.access.BeanFactoryLocator;  
    23. import org.springframework.beans.factory.access.BeanFactoryReference;  
    24.   
    25. /** 
    26.  * BeanFactoryLocator used for injecting Spring application context into JBPM. 
    27.  * The difference/advantage over the traditional SingletonBeanFactoryLocator is 
    28.  * that it does not parse a bean factory definition; it is used internally by 
    29.  * the jbpmSessionFactoryBean and it will register the bean factory/application 
    30.  * context containing it automatically under the name and and aliases of the 
    31.  * bean. If there is only one BeanFactory registered then a null value can be 
    32.  * used with setBeanName method. <p/> Note that in most cases, you don't have to 
    33.  * use this class directly since it is used internally by 
    34.  * LocalJbpmConfigurationFactoryBean. 
    35.  *  
    36.  * @author Costin Leau 
    37.  *  
    38.  */  
    39. public class JbpmFactoryLocator implements BeanFactoryLocator, BeanFactoryAware, BeanNameAware {  
    40.   
    41.     private static final Log logger = LogFactory.getLog(JbpmFactoryLocator.class);  
    42.   
    43.     // default factory name (for nested classes)  
    44.     private String factoryName = JbpmFactoryLocator.class.getName();  
    45.   
    46.     // alias/bean name to BeanFactory  
    47.     protected static final Map<String, BeanFactory> beanFactories = new HashMap<String, BeanFactory>();  
    48.   
    49.     // beanfactory to alias/bean name map  
    50.     protected static final Map<BeanFactory,List<String>> beanFactoriesNames = new HashMap<BeanFactory, List<String>>();  
    51.   
    52.     protected static final Map<BeanFactory, Integer> referenceCounter = new HashMap<BeanFactory, Integer>();  
    53.   
    54.     protected static boolean canUseDefaultBeanFactory = true;  
    55.   
    56.     protected static BeanFactory defaultFactory = null;  
    57.   
    58.     /** 
    59.      * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory) 
    60.      */  
    61.     public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {  
    62.   
    63.         // add the factory as default if possible (if it's the only one)  
    64.         synchronized (JbpmFactoryLocator.class) {  
    65.             if (canUseDefaultBeanFactory) {  
    66.                 if (defaultFactory == null) {  
    67.                     defaultFactory = beanFactory;  
    68.                     if (logger.isDebugEnabled())  
    69.                         logger.debug("default beanFactoryReference=" + defaultFactory);  
    70.                 }  
    71.                 else {  
    72.                     if (logger.isDebugEnabled())  
    73.                         logger.debug("more then one beanFactory - default not possible to determine");  
    74.                     canUseDefaultBeanFactory = false;  
    75.                     defaultFactory = null;  
    76.                 }  
    77.             }  
    78.         }  
    79.   
    80.         // add name  
    81.         addToMap(factoryName, beanFactory);  
    82.         Integer counter = (Integer) referenceCounter.get(beanFactory);  
    83.   
    84.         if (counter == null)  
    85.             referenceCounter.put(beanFactory, new Integer(0));  
    86.   
    87.         // add aliases  
    88.         String[] aliases = beanFactory.getAliases(factoryName);  
    89.         List<String> names = new ArrayList<String>(1 + aliases.length);  
    90.         names.add(factoryName);  
    91.   
    92.         for (int i = 0; i < aliases.length; i++) {  
    93.             addToMap(aliases[i], beanFactory);  
    94.             names.add(aliases[i]);  
    95.         }  
    96.   
    97.         // append previous found names  
    98.         List<String> previousNames = (List<String>) beanFactoriesNames.get(beanFactory);  
    99.         if (previousNames != null)  
    100.             names.addAll(previousNames);  
    101.   
    102.         beanFactoriesNames.put(beanFactory, names);  
    103.   
    104.     }  
    105.   
    106.     protected void addToMap(String fName, BeanFactory factory) {  
    107.         if (logger.isDebugEnabled())  
    108.             logger.debug("adding key=" + fName + " w/ reference=" + factory);  
    109.   
    110.         synchronized (beanFactories) {  
    111.             // override check  
    112.             if (beanFactories.containsKey(fName))  
    113.                 throw new IllegalArgumentException("a beanFactoryReference already exists for key " + factoryName);  
    114.             beanFactories.put(fName, factory);  
    115.         }  
    116.     }  
    117.   
    118.     protected void removeReference(BeanFactory factory) {  
    119.         synchronized (referenceCounter) {  
    120.             Integer count = (Integer) referenceCounter.get(factory);  
    121.             // decrement counter  
    122.             int counter = count.intValue();  
    123.             counter--;  
    124.             if (counter == 0) {  
    125.                 if (logger.isDebugEnabled())  
    126.                     logger.debug("removing factory references under key " + factoryName);  
    127.                 referenceCounter.remove(factory);  
    128.   
    129.                 // reset also default beanFactory  
    130.                 if (referenceCounter.isEmpty()) {  
    131.                     canUseDefaultBeanFactory = true;  
    132.                     defaultFactory = null;  
    133.                 }  
    134.                 List<String> names = (List<String>) beanFactoriesNames.get(factory);  
    135.                 beanFactoriesNames.remove(factory);  
    136.   
    137.                 synchronized (beanFactories) {  
    138.                     for (Iterator iter = names.iterator(); iter.hasNext();) {  
    139.                         beanFactories.remove(iter.next());  
    140.                     }  
    141.                 }  
    142.             }  
    143.   
    144.             else  
    145.                 referenceCounter.put(factory, new Integer(counter));  
    146.         }  
    147.     }  
    148.   
    149.     /** 
    150.      * @see org.springframework.beans.factory.access.BeanFactoryLocator#useBeanFactory(java.lang.String) 
    151.      */  
    152.     public BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException {  
    153.         // see if there is a default FactoryBean  
    154.         BeanFactory factory;  
    155.   
    156.         if (factoryKey == null) {  
    157.             if (!canUseDefaultBeanFactory)  
    158.                 throw new IllegalArgumentException(  
    159.                         "a non-null factoryKey needs to be specified as there are more then one factoryKeys available ");  
    160.             factory = defaultFactory;  
    161.         }  
    162.         else {  
    163.             factory = (BeanFactory) beanFactories.get(factoryKey);  
    164.             if (factory == null)  
    165.                 throw new IllegalArgumentException("there is no beanFactory under key " + factoryKey);  
    166.         }  
    167.   
    168.         // increment counter  
    169.         synchronized (referenceCounter) {  
    170.             Integer counter = (Integer) referenceCounter.get(factory);  
    171.             referenceCounter.put(factory, new Integer(counter.intValue() + 1));  
    172.         }  
    173.   
    174.         final BeanFactory finalFactory = factory;  
    175.   
    176.         // simple implementation  
    177.         return new BeanFactoryReference() {  
    178.             private BeanFactory fact = finalFactory;  
    179.   
    180.             public BeanFactory getFactory() {  
    181.                 if (this.fact == null)  
    182.                     throw new IllegalArgumentException("beanFactory already released");  
    183.                 return this.fact;  
    184.             }  
    185.   
    186.             public void release() throws FatalBeanException {  
    187.                 if (fact != null) {  
    188.                     removeReference(fact);  
    189.                     // remove the factory reference  
    190.                     this.fact = null;  
    191.                 }  
    192.             }  
    193.         };  
    194.     }  
    195.   
    196.     /** 
    197.      * @see org.springframework.beans.factory.BeanNameAware#setTargetBean(java.lang.String) 
    198.      */  
    199.     public void setBeanName(String name) {  
    200.         factoryName = name;  
    201.     }  
    202.   
    203. }  

     把这个类配置成spring的bean:

    Xml代码  收藏代码
    1. <bean id="baseAutowire" class="com.founder.jbpm.util.JbpmFactoryLocator">  
    2.     </bean>  

     

    定义一个类BaseAutowire:

    Java代码  收藏代码
    1. package com.founder.jbpm.util;  
    2.   
    3. import org.springframework.beans.factory.BeanFactory;  
    4. import org.springframework.beans.factory.access.BeanFactoryLocator;  
    5. import org.springframework.beans.factory.access.BeanFactoryReference;  
    6. import org.springframework.beans.factory.config.AutowireCapableBeanFactory;  
    7.   
    8. public class BaseAutowire {  
    9.   
    10.       //arg1:向哪个类进行属性注入    
    11.                 //arg2:按照那种方式注入:按类型、或者名称....此处按照类型    
    12.                 //arg2:是否检查依赖关系,一般情况下为true要检查依赖关系。    
    13.          public BaseAutowire() {    
    14.              ((AutowireCapableBeanFactory)retrieveBeanFactory())    
    15.                  .autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);    
    16.          }    
    17.              
    18.          protected BeanFactory retrieveBeanFactory() {    
    19.              BeanFactoryLocator factoryLocator = new JbpmFactoryLocator();    
    20.              BeanFactoryReference factory = factoryLocator.useBeanFactory(null);    
    21.              if (factory == null)    
    22.                  throw new IllegalArgumentException("no beanFactory found under key=" + null);    
    23.          
    24.              try {    
    25.                  return factory.getFactory();    
    26.              }    
    27.              finally {    
    28.                  factory.release();    
    29.              }    
    30.          }    
    31. }  

        让RoleAssignmentHandler继承BaseAutowire即可:

    Java代码  收藏代码
    1. public class RoleAssignmentHandler extends BaseAutowire implements AssignmentHandler {  
    2.   
    3.     private static final long serialVersionUID = 1L;  
    4.       
    5.         private  UserService userService;  
    6.       
    7.     public void assign(Assignable arg0, OpenExecution arg1) throws Exception {  
    8.         // TODO Auto-generated method stub  
    9.         userService.getUserById("");//调用userService的方法  
    10.     }  
    11.   
    12.   
    13.   
    14.         public ProcessEngine getProcessEngine() {  
    15.         return processEngine;  
    16.     }  
    17.   
    18.   
    19.     public void setProcessEngine(ProcessEngine processEngine) {  
    20.         this.processEngine = processEngine;  
    21.     }     
    22. }  

     

  • 相关阅读:
    繁体解决方案一,ASP,JSP,PHP,DotNet任何开发通用
    18.观察者模式(Observer Pattern)
    存储过程小技巧(2)从动态查询SQL中返回值给变量
    DotNet学习
    询问:有没有用C#写的C/S模式下的网页编辑工具
    dotNet繁体解决方案
    svn感叹号大全
    svn中出现红色感叹号
    Varnish配置,Error 503解决之道
    varnish清除缓存的方法
  • 原文地址:https://www.cnblogs.com/toSeeMyDream/p/4370085.html
Copyright © 2011-2022 走看看