In our blog Activiti Service Task, we showed how to implement a service task by either using a Java Delegate or a Spring Bean. But Alfresco recommends embedding or calling Spring Beans from within a Java Delegate Activiti as best-approach. So extending our Activiti Service Task blog, we are going to show how to embed or call a Spring bean within a Java Delegate.
Embedding Spring bean within Java Delegate
We are going to use the Spring Bean (myFirstSpringBean) and Java Delegate class (MyFirstJavaDelegate) we created in our Activiti Service Task blog for this blog. So if you have not viewed our previous blog and do not have any notion of Spring bean and Java Delegate then please do check out the Activiti Service Task blog first.
So before we start with the implementation, one thing to understand is that since the Java Delegate is not a spring bean we cannot use the @Autowired annotation to inject our spring bean hence the need to use Expression.
So as shown below, we start by defining an instance of our Spring Bean class and Expression into our Java delegate as follows and getters and setters for our Expression.
private MyFirstSpringBean myFirstSpringBean;
public Expression getMyFirstSpringBeanExpression() {
return myFirstSpringBeanExpression;
}
public void setMyFirstSpringBeanExpression(Expression myFirstSpringBeanExpression) {
this.myFirstSpringBeanExpression = myFirstSpringBeanExpression;
}
Next let’s look at our execute Method
public void execute(DelegateExecution execution) throws Exception {
System.out.println(“Hello from My First Java delegate class”);
}
Once we have output “Hello from My First Java delegate class ” we will delegate the execution to the Spring bean and we will use the myFirstSpringBeanExpression to set the value of our Spring Bean instance.
if(myFirstSpringBean == null) { myFirstSpringBean = (MyFirstSpringBean) myFirstSpringBeanExpression.getValue(execution); }
And now that we have initialised our Spring Bean we can use it to call it method as follows
myFirstSpringBean.()execute
Leveraging the embedded spring bean within the Java Delegate from Activiti
We are going to use the same workflow we showed for Activiti Service Task blog and will need to modify the Java Delegate service task.
We need to edit the Class Fields property as shown below;
In the Name field we need to put the name of the our service task expression we defined in our Java Delegate class and in this case myFirstSpringBeanExpression.
In the Expression field we need to put the name of the bean as identified in the spring context (remember @Component(“myFirstSpringBean”))
When the workflow process is run, the following should be logged in the console
Hello from My First Java delegate class
Hello from My First Spring Bean
Hello from My First Spring Bean