13.3. Spring

A Spring XML configuration file can be used to easily define and configure knowledge bases and sessions in a Spring environment, making it possible to access a session and invoke processes from within a Spring application.
The Example SPring Configuration File below sets up a new session based on a knowledge base with one process definition loaded from the classpath.

Example 13.2. Example Spring Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jbpm="http://drools.org/schema/drools-spring"       
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                           http://drools.org/schema/drools-spring org/drools/container/spring/drools-spring-1.2.0.xsd>
   
  <jbpm:kbase id="kbase">
    <jbpm:resources>
      <jbpm:resource type="BPMN2" source="classpath:HelloWorld.bpmn2"/>
    </jbpm:resources>
  </jbpm:kbase>

  <jbpm:ksession id="ksession" type="stateful" kbase="kbase" />

</beans>
The following code loads the above Spring configuration, retrieves the session, and starts the process:
ClassPathXmlApplicationContext context = 
    new ClassPathXmlApplicationContext("spring-conf.xml");
StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) context.getBean("ksession");
ksession.startProcess("com.sample.HelloWorld");
Note that you can also inject the session in one of your domain objects; for example, add the following fragment in the configuration file:
<bean id="myObject" class="org.jbpm.sample.MyObject">
  <property name="session" ref="ksession" />
</bean>
As a result, the session will be injected into the domain object and can then be accessed directly. For example:
public class MyObject {
  private StatefulKnowledgeSession ksession;
  public void setSession(StatefulKnowledgeSession ksession) {
    this.ksession = ksession;
  }
  public void doSomething() {
    ksession.startProcess("com.sample.HelloWorld");
  }
}