在JBPM的Handle类中调用Spring管理的类
我们在使用JBPM定义流程的时候经常要在流程定义文件中加入一个继承xxxHandler的类来实现我们的业务逻辑判断或者其他的需求,在这个类中一般都是用Spring的Application来获取,而这种情况每次都需要加载配置。
假设使用的Handle类是RoleAssignmentHandler,需要注入的属性石UserService, 以下有几种解决办法:
1、在RoleAssignmentHandler中把UserService声明成static
- //@Component
- public class RoleAssignmentHandler implements AssignmentHandler {
- private static final long serialVersionUID = 1L;
- //(注解式的Resource不能用在static修饰的字段)
- //@Resource(name="userService")//配置static的userService
- private static UserService userService;
- public void assign(Assignable arg0, OpenExecution arg1) throws Exception {
- userService.getUserById("");//调用userService的方法
- }
- public void setUserService(UserService userService) {
- RoleAssignmentHandler.userService = userService;
- }
- }
为什么定义成静态的就可以呢?我们都知道静态变量时类级别的变量,所有这个类的实例共享一份,那么第一次Spring给我们创建这个对象的时 候,userService有值了等到第二次JBPM给我们创建这个对象的时候由于UserService是static的,所以他依然会有值 所以通过这种方法我们可以得到UserService对象,但是我们并不推荐这种方法,因为确实有点浪费内存资源 Spring明明已经把这个对象创建好了但是我们却没有去使用这个对象而是去使用了另一个由JBPM给我们创建的一个对象,但这种方法是可行的。
2、自动注入。
首先定义一个类BeanAutowire实现BeanFactoryAware接口,并把这个类交给spring管理。
- @Component
- public class BeanAutowire implements BeanFactoryAware{
- private static BeanFactory beanFactory;
- public BeanAutowire() {
- if (null != beanFactory) {
- ((AutowireCapableBeanFactory)beanFactory).autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
- }
- }
- public void setBeanFactory(BeanFactory arg0) throws BeansException {
- // TODO Auto-generated method stub
- BeanAutowire.beanFactory=arg0;
- }
- }
然后让RoleAssignmentHandler类继承BeanAutowire:
- public class RoleAssignmentHandler extends BeanAutowire implements AssignmentHandler {
- private static final long serialVersionUID = 1L;
- @Resource(name="userService")
- private UserService userService;
- public void assign(Assignable arg0, OpenExecution arg1) throws Exception {
- // TODO Auto-generated method stub
- userService.getUserById("");//调用userService的方法
- }
- public void setUserService(UserService userService) {
- RoleAssignmentHandler.userService = userService;
- }
- }
这样,在spring初始化的时候会把BeanFactory注入到BeanAutowire中去,在jbpm每次使用Handle类时候会new一个Handle的实例,这时候会首先调用父类的构造方法:
- public BeanAutowire() {
- if (null != beanFactory) {
- ((AutowireCapableBeanFactory)beanFactory).autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
- }
- }
把需要注入的对象注入到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他都是有值的,然后返回这个值:
- protected BeanFactory retrieveBeanFactory() {
- BeanFactoryLocator factoryLocator = new JbpmFactoryLocator();
- BeanFactoryReference factory = factoryLocator.useBeanFactory(null);
- if (factory == null)
- throw new IllegalArgumentException("no beanFactory found under key=" + null);
- try {
- return factory.getFactory();
- }
- finally {
- factory.release();
- }
- }
以下是这个方法的具体实施办法:
这里,由于springmodules跟jbpm4.4的集成有些问题,所以单独把JbpmFactoryLocator这个类拿了出来,修改一下相关类的引入就可以使用:
- /**
- * Created on Jan 24, 2006
- *
- * $Id: JbpmFactoryLocator.java,v 1.3 2006-12-06 14:13:18 costin Exp $
- * $Revision: 1.3 $
- */
- package com.founder.jbpm.util;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.beans.BeansException;
- import org.springframework.beans.FatalBeanException;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.BeanFactoryAware;
- import org.springframework.beans.factory.BeanNameAware;
- import org.springframework.beans.factory.access.BeanFactoryLocator;
- import org.springframework.beans.factory.access.BeanFactoryReference;
- /**
- * BeanFactoryLocator used for injecting Spring application context into JBPM.
- * The difference/advantage over the traditional SingletonBeanFactoryLocator is
- * that it does not parse a bean factory definition; it is used internally by
- * the jbpmSessionFactoryBean and it will register the bean factory/application
- * context containing it automatically under the name and and aliases of the
- * bean. If there is only one BeanFactory registered then a null value can be
- * used with setBeanName method. <p/> Note that in most cases, you don't have to
- * use this class directly since it is used internally by
- * LocalJbpmConfigurationFactoryBean.
- *
- * @author Costin Leau
- *
- */
- public class JbpmFactoryLocator implements BeanFactoryLocator, BeanFactoryAware, BeanNameAware {
- private static final Log logger = LogFactory.getLog(JbpmFactoryLocator.class);
- // default factory name (for nested classes)
- private String factoryName = JbpmFactoryLocator.class.getName();
- // alias/bean name to BeanFactory
- protected static final Map<String, BeanFactory> beanFactories = new HashMap<String, BeanFactory>();
- // beanfactory to alias/bean name map
- protected static final Map<BeanFactory,List<String>> beanFactoriesNames = new HashMap<BeanFactory, List<String>>();
- protected static final Map<BeanFactory, Integer> referenceCounter = new HashMap<BeanFactory, Integer>();
- protected static boolean canUseDefaultBeanFactory = true;
- protected static BeanFactory defaultFactory = null;
- /**
- * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
- */
- public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {
- // add the factory as default if possible (if it's the only one)
- synchronized (JbpmFactoryLocator.class) {
- if (canUseDefaultBeanFactory) {
- if (defaultFactory == null) {
- defaultFactory = beanFactory;
- if (logger.isDebugEnabled())
- logger.debug("default beanFactoryReference=" + defaultFactory);
- }
- else {
- if (logger.isDebugEnabled())
- logger.debug("more then one beanFactory - default not possible to determine");
- canUseDefaultBeanFactory = false;
- defaultFactory = null;
- }
- }
- }
- // add name
- addToMap(factoryName, beanFactory);
- Integer counter = (Integer) referenceCounter.get(beanFactory);
- if (counter == null)
- referenceCounter.put(beanFactory, new Integer(0));
- // add aliases
- String[] aliases = beanFactory.getAliases(factoryName);
- List<String> names = new ArrayList<String>(1 + aliases.length);
- names.add(factoryName);
- for (int i = 0; i < aliases.length; i++) {
- addToMap(aliases[i], beanFactory);
- names.add(aliases[i]);
- }
- // append previous found names
- List<String> previousNames = (List<String>) beanFactoriesNames.get(beanFactory);
- if (previousNames != null)
- names.addAll(previousNames);
- beanFactoriesNames.put(beanFactory, names);
- }
- protected void addToMap(String fName, BeanFactory factory) {
- if (logger.isDebugEnabled())
- logger.debug("adding key=" + fName + " w/ reference=" + factory);
- synchronized (beanFactories) {
- // override check
- if (beanFactories.containsKey(fName))
- throw new IllegalArgumentException("a beanFactoryReference already exists for key " + factoryName);
- beanFactories.put(fName, factory);
- }
- }
- protected void removeReference(BeanFactory factory) {
- synchronized (referenceCounter) {
- Integer count = (Integer) referenceCounter.get(factory);
- // decrement counter
- int counter = count.intValue();
- counter--;
- if (counter == 0) {
- if (logger.isDebugEnabled())
- logger.debug("removing factory references under key " + factoryName);
- referenceCounter.remove(factory);
- // reset also default beanFactory
- if (referenceCounter.isEmpty()) {
- canUseDefaultBeanFactory = true;
- defaultFactory = null;
- }
- List<String> names = (List<String>) beanFactoriesNames.get(factory);
- beanFactoriesNames.remove(factory);
- synchronized (beanFactories) {
- for (Iterator iter = names.iterator(); iter.hasNext();) {
- beanFactories.remove(iter.next());
- }
- }
- }
- else
- referenceCounter.put(factory, new Integer(counter));
- }
- }
- /**
- * @see org.springframework.beans.factory.access.BeanFactoryLocator#useBeanFactory(java.lang.String)
- */
- public BeanFactoryReference useBeanFactory(String factoryKey) throws BeansException {
- // see if there is a default FactoryBean
- BeanFactory factory;
- if (factoryKey == null) {
- if (!canUseDefaultBeanFactory)
- throw new IllegalArgumentException(
- "a non-null factoryKey needs to be specified as there are more then one factoryKeys available ");
- factory = defaultFactory;
- }
- else {
- factory = (BeanFactory) beanFactories.get(factoryKey);
- if (factory == null)
- throw new IllegalArgumentException("there is no beanFactory under key " + factoryKey);
- }
- // increment counter
- synchronized (referenceCounter) {
- Integer counter = (Integer) referenceCounter.get(factory);
- referenceCounter.put(factory, new Integer(counter.intValue() + 1));
- }
- final BeanFactory finalFactory = factory;
- // simple implementation
- return new BeanFactoryReference() {
- private BeanFactory fact = finalFactory;
- public BeanFactory getFactory() {
- if (this.fact == null)
- throw new IllegalArgumentException("beanFactory already released");
- return this.fact;
- }
- public void release() throws FatalBeanException {
- if (fact != null) {
- removeReference(fact);
- // remove the factory reference
- this.fact = null;
- }
- }
- };
- }
- /**
- * @see org.springframework.beans.factory.BeanNameAware#setTargetBean(java.lang.String)
- */
- public void setBeanName(String name) {
- factoryName = name;
- }
- }
把这个类配置成spring的bean:
- <bean id="baseAutowire" class="com.founder.jbpm.util.JbpmFactoryLocator">
- </bean>
定义一个类BaseAutowire:
- package com.founder.jbpm.util;
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.access.BeanFactoryLocator;
- import org.springframework.beans.factory.access.BeanFactoryReference;
- import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
- public class BaseAutowire {
- //arg1:向哪个类进行属性注入
- //arg2:按照那种方式注入:按类型、或者名称....此处按照类型
- //arg2:是否检查依赖关系,一般情况下为true要检查依赖关系。
- public BaseAutowire() {
- ((AutowireCapableBeanFactory)retrieveBeanFactory())
- .autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
- }
- protected BeanFactory retrieveBeanFactory() {
- BeanFactoryLocator factoryLocator = new JbpmFactoryLocator();
- BeanFactoryReference factory = factoryLocator.useBeanFactory(null);
- if (factory == null)
- throw new IllegalArgumentException("no beanFactory found under key=" + null);
- try {
- return factory.getFactory();
- }
- finally {
- factory.release();
- }
- }
- }
让RoleAssignmentHandler继承BaseAutowire即可:
- public class RoleAssignmentHandler extends BaseAutowire implements AssignmentHandler {
- private static final long serialVersionUID = 1L;
- private UserService userService;
- public void assign(Assignable arg0, OpenExecution arg1) throws Exception {
- // TODO Auto-generated method stub
- userService.getUserById("");//调用userService的方法
- }
- public ProcessEngine getProcessEngine() {
- return processEngine;
- }
- public void setProcessEngine(ProcessEngine processEngine) {
- this.processEngine = processEngine;
- }
- }
在JBPM的Handle类中调用Spring管理的类的更多相关文章
- 170630、springboot编程之普通类中调用spring管理的bean对象
我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,想直接使用 ...
- 在普通类中获取Spring管理的bean
1.在项目中添加下面的类: import org.springframework.context.ApplicationContext; import org.springframework.cont ...
- tomcat启动后,在普通java类中获取spring管理的bean和ServletContext,(经过验证,可以取到)
//从spring容易中获取bean public static Object getBean(String beanName){ ApplicationContext context = Conte ...
- Servlet中获取Spring管理的bean
描述: 在Servlet中调用Spring管理的接口,可以使Dao/Service/ServiceImpl. 前提是在调用的bean中有注解: @Repository("beanName&q ...
- Spring MVC普通类或工具类中调用service报空空指针的解决办法(调用service报java.lang.NullPointerException)
当我们在非Controller类中应用service的方法是会报空指针,如图: 这是因为Spring MVC普通类或工具类中调用service报空null的解决办法(调用service报java.la ...
- springboot 项目中在普通类中调用dao层的mapper 出现空指针异常
项目中我遇到同样的问题 特记载一下 有两种方式 一. 该类使用@Component注解 添加一个本类类型的静态字段 创建一个初始化方法,贴上@PostConstruct 标签,用于注入bean 创建方 ...
- spring管理的类如何调用非spring管理的类
spring管理的类如何调用非spring管理的类. 就是使用一个spring提供的感知概念,在容器启动的时候,注入上下文即可. 下面是一个工具类. import org.springframewor ...
- C#在派生类中调用基类成员
一.在派生类中调用基类成员 在C#的派生类中,我们可以使用base关键字调用基类中的公有或者受保护成员.这些成员只能是构造函数.实例方法或者实例属性. base关键字调用基类成员的语法格式如下: ba ...
- 谈谈java中静态变量与静态方法在有继承关系的两个类中调用
谈谈java中静态变量与静态方法在有继承关系的两个类中调用 学习的中如果遇到不明白或者不清楚的的时候,就是自己做些测试,自己去试试,这次我就做一个关于静态变量和静态方法在有继承关系的两个类中的问题测试 ...
随机推荐
- Luogu 3690 Link Cut Tree
Luogu 3690 Link Cut Tree \(LCT\) 模板题.可以参考讲解和这份码风(个人认为)良好的代码. 注意用 \(set\) 来维护实际图中两点是否有直接连边,否则无脑 \(Lin ...
- python(三):函数
一.函数.名称空间与作用域 1.函数的构成 python有三种层次的抽象:(1)程序可分成多个模块:(2)每个模块包含多条语句:(3)每条语句对对象进行操作.函数大致处于第二层.函数有它的定义格式.参 ...
- MYSQL在当前日期的基础上加上N(年月日分秒)
//把id为1的那条数据的开始时间改为现在 结束时间改为开始时间的1个月后 update 表明 set begintime=now(),endtime=date_add(NOW(), interv ...
- python正则的使用
python的正则是通过re模块的支持 匹配的3个函数 match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则返回none: re.match(pattern, st ...
- uuid 了解
什么是UUID? UUID是Universally Unique Identifier的缩写,它是在一定的范围内(从特定的名字空间到全球)唯一的机器生成的标识符.UUID具有以下涵义: 经由一定的算法 ...
- 最短路径问题的Dijkstra算法
问题 最短路径问题的Dijkstra算法 是由荷兰计算机科学家艾兹赫尔·戴克斯特拉提出.迪科斯彻算法使用了广度优先搜索解决非负权有向图的单源最短路径问题,算法终于得到一个最短路径树> ...
- 常见企业IT支撑【4、gitlab代码管理工具】
安装方式可借鉴http://www.cnblogs.com/juandx/p/5339254.html 安装方式
- licode从客户端到连上信令服务器流程
var config = {audio: true, video: true, data: true, screen: screen, videoSize: [640, 480, 640, 480], ...
- NGINX conf 配置文件中的变量大全 可用变量列表及说明
$args #这个变量等于请求行中的参数.$content_length #请求头中的Content-length字段.$content_type #请求头中的Content-Type字段.$docu ...
- java web 程序---刷新页面次数进一步
<%@ page language="java" import="java.util.*" pageEncoding="gb2312" ...