在Activiti中使用TaskListener时,若是是使用的类型是Class时,使用Spring是没法自动注入须要的bean的,网上查了下,缘由是Acitivi引擎会在内部使用Class.newInstance(...)的方式建立一个该类的对象,这个对象不被Spring管理,因此Sping是没法给这个对象注入咱们须要的beanjava
怎么办呢?使用ApplicationContext把须要的bean取出来手动赋值,简单粗暴。web
package cn.lixuelong.demo; import org.activiti.engine.IdentityService; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import org.activiti.engine.identity.Group; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; /** * Created by long on 2017/12/5. */ public class AssigneeListenerImpl implements TaskListener { public AssigneeListenerImpl() { //从ApplicationContext中取到须要的bean,手动赋值 ApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); identityService = (IdentityService) context.getBean("identityService"); } private IdentityService identityService; @Override public void notify(DelegateTask delegateTask) { String taskName = delegateTask.getName(); String groupName; if ("经理".equals(taskName)) { groupName = "经理"; } else if ("客服".equals(taskName)) { groupName = "客服"; } else { return; } Group group = identityService.createGroupQuery().groupName(groupName).singleResult(); delegateTask.addCandidateGroup(group.getId()); } }
方法笨了点,可是简单省事,适合在bean少的状况下使用spring
让Spring管理你的Listener类(一样实现了TaskListener接口),好比说我有个MyListener交给Spring管理了,给这个类起名为"myListener",配置方式以下图ide
而后它就是个被Spring管理的Listener了spa