BPMN: основы Business Process Model and Notation
Business Process Model and Notation (BPMN) — это международный стандарт для графического представления бизнес-процессов. BPMN 2.0 предоставляет стандартизированную нотацию для моделирования, анализа и оптимизации бизнес-рабочих процессов.
Что такое BPMN?
BPMN представляет собой графический язык нотации для описания бизнес-процессов. Он был разработан Object Management Group (OMG) и с 2011 года стандартизирован как ISO-норма 19510.
Основные характеристики BPMN
- Стандартизированная нотация: единые символы и правила
- Графическое представление: визуальное моделирование процессов
- Независимость от технологии: кроссплатформенное применение
- Исполняемые процессы: прямое внедрение в Workflow-движки
Основные элементы BPMN
1. Flow Objects (объекты потока)
Events (события)
События являются триггерами или результатами в процессе:
<!-- Start Event -->
<bpmn:startEvent id="startEvent" name="Prozess starten"/>
<!-- End Event -->
<bpmn:endEvent id="endEvent" name="Prozess beenden"/>
<!-- Intermediate Event -->
<bpmn:intermediateCatchEvent id="timerEvent" name="Wartezeit">
<bpmn:timerEventDefinition/>
</bpmn:intermediateCatchEvent>
Типы событий:
- Start Event: начало процесса
- End Event: завершение процесса
- Intermediate Event: промежуточные события
Activities (операции)
Операции представляют рабочие шаги в процессе:
<!-- Task -->
<bpmn:task id="task1" name="Daten eingeben"/>
<!-- User Task -->
<bpmn:userTask id="userTask1" name="Genehmigung erforderlich"/>
<!-- Service Task -->
<bpmn:serviceTask id="serviceTask1" name="Automatische Prüfung"/>
<!-- Sub-Process -->
<bpmn:subProcess id="subProcess1" name="Detailprozess">
<bpmn:startEvent id="subStart"/>
<bpmn:task id="subTask1"/>
<bpmn:endEvent id="subEnd"/>
</bpmn:subProcess>
Gateways (шлюзы)
Шлюзы управляют потоком процесса:
<!-- Exclusive Gateway (XOR) -->
<bpmn:exclusiveGateway id="gateway1" name="Entscheidung"/>
<!-- Parallel Gateway (AND) -->
<bpmn:parallelGateway id="gateway2" name="Parallelisierung"/>
<!-- Inclusive Gateway (OR) -->
<bpmn:inclusiveGateway id="gateway3" name="Mehrfachauswahl"/>
2. Connecting Objects (объекты соединения)
Sequence Flows (потоки последовательности)
Соединяют операции и шлюзы:
<bpmn:sequenceFlow id="flow1" sourceRef="startEvent" targetRef="task1"/>
<bpmn:sequenceFlow id="flow2" sourceRef="task1" targetRef="gateway1"/>
Message Flows (потоки сообщений)
Коммуникация между различными процессами:
<bpmn:messageFlow id="msgFlow1" sourceRef="pool1" targetRef="pool2"/>
Associations (ассоциации)
Связывают артефакты с объектами потока:
<bpmn:association id="assoc1" sourceRef="dataObject1" targetRef="task1"/>
3. Pools and Lanes
Pools (бассейны)
Представляют участников в процессе:
<bpmn:pool id="pool1" name="Abteilung A">
<bpmn:laneSet>
<bpmn:lane id="lane1" name="Mitarbeiter"/>
<bpmn:lane id="lane2" name="Management"/>
</bpmn:laneSet>
</bpmn:pool>
Lanes (дорожки)
Организуют операции внутри бассейнов:
<bpmn:lane id="lane1" name="Vertrieb">
<bpmn:flowNodeRef>task1</bpmn:flowNodeRef>
<bpmn:flowNodeRef>gateway1</bpmn:flowNodeRef>
</bpmn:lane>
4. Data Objects
Data Objects
Представляют информацию в процессе:
<bpmn:dataObject id="data1" name="Kundendaten"/>
<bpmn:dataStoreReference id="store1" name="Datenbank"/>
Практический пример BPMN
Моделирование процесса заказа
<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
xmlns:dc="http://www.omg.org/spec/DD/20100524/DC"
xmlns:di="http://www.omg.org/spec/DD/20100524/DI"
id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn">
<bpmn:process id="Bestellprozess" isExecutable="false">
<!-- Start Event -->
<bpmn:startEvent id="StartEvent_1" name="Bestellung eingegangen">
<bpmn:outgoing>Flow_1</bpmn:outgoing>
</bpmn:startEvent>
<!-- Task: Bestellung prüfen -->
<bpmn:userTask id="Task_1" name="Bestellung prüfen">
<bpmn:incoming>Flow_1</bpmn:incoming>
<bpmn:outgoing>Flow_2</bpmn:outgoing>
</bpmn:userTask>
<!-- Gateway: Entscheidung -->
<bpmn:exclusiveGateway id="Gateway_1" name="Bestellung gültig?">
<bpmn:incoming>Flow_2</bpmn:incoming>
<bpmn:outgoing>Flow_3</bpmn:outgoing>
<bpmn:outgoing>Flow_4</bpmn:outgoing>
</bpmn:exclusiveGateway>
<!-- Task: Lager prüfen -->
<bpmn:serviceTask id="Task_2" name="Lagerbestand prüfen">
<bpmn:incoming>Flow_3</bpmn:incoming>
<bpmn:outgoing>Flow_5</bpmn:outgoing>
</bpmn:serviceTask>
<!-- Task: Ablehnung -->
<bpmn:userTask id="Task_3" name="Bestellung ablehnen">
<bpmn:incoming>Flow_4</bpmn:incoming>
<bpmn:outgoing>Flow_6</bpmn:outgoing>
</bpmn:userTask>
<!-- End Events -->
<bpmn:endEvent id="EndEvent_1" name="Bestellung bestätigt">
<bpmn:incoming>Flow_5</bpmn:incoming>
</bpmn:endEvent>
<bpmn:endEvent id="EndEvent_2" name="Bestellung abgelehnt">
<bpmn:incoming>Flow_6</bpmn:incoming>
</bpmn:endEvent>
<!-- Sequence Flows -->
<bpmn:sequenceFlow id="Flow_1" sourceRef="StartEvent_1" targetRef="Task_1"/>
<bpmn:sequenceFlow id="Flow_2" sourceRef="Task_1" targetRef="Gateway_1"/>
<bpmn:sequenceFlow id="Flow_3" name="Ja" sourceRef="Gateway_1" targetRef="Task_2"/>
<bpmn:sequenceFlow id="Flow_4" name="Nein" sourceRef="Gateway_1" targetRef="Task_3"/>
<bpmn:sequenceFlow id="Flow_5" sourceRef="Task_2" targetRef="EndEvent_1"/>
<bpmn:sequenceFlow id="Flow_6" sourceRef="Task_3" targetRef="EndEvent_2"/>
</bpmn:process>
</bpmn:definitions>
Типы BPMN шлюзов в деталях
Exclusive Gateway (XOR)
Может быть выбран только один исходящий путь:
// Java реализация Exclusive Gateway
public class ExclusiveGateway {
private Map<String, String> conditions;
public String evaluateCondition(Map<String, Object> context) {
for (Map.Entry<String, String> condition : conditions.entrySet()) {
if (evaluateExpression(condition.getKey(), context)) {
return condition.getValue();
}
}
return null; // Default Path
}
private boolean evaluateExpression(String expression, Map<String, Object> context) {
// Реализация вычисления условия
return context.containsKey(expression) && (Boolean) context.get(expression);
}
}
Parallel Gateway (AND)
Все исходящие пути активируются одновременно:
// Java реализация Parallel Gateway
public class ParallelGateway {
private List<String> outgoingFlows;
private List<String> incomingFlows;
public List<String> execute() {
if (allIncomingFlowsCompleted()) {
return new ArrayList<>(outgoingFlows);
}
return Collections.emptyList();
}
private boolean allIncomingFlowsCompleted() {
// Проверка того, что все входящие потоки завершены
return true; // Упрощённая реализация
}
}
Inclusive Gateway (OR)
Несколько исходящих потоков могут быть выбраны одновременно:
// Java Implementierung eines Inclusive Gateway
public class InclusiveGateway {
private List<ConditionFlow> conditionFlows;
public List<String> evaluateConditions(Map<String, Object> context) {
List<String> activeFlows = new ArrayList<>();
for (ConditionFlow conditionFlow : conditionFlows) {
if (conditionFlow.evaluate(context)) {
activeFlows.add(conditionFlow.getTargetId());
}
}
return activeFlows;
}
}
BPMN События и их типы
Timer Events
События, управляемые временем:
<bpmn:intermediateCatchEvent id="timerEvent" name="Wartezeit">
<bpmn:timerEventDefinition>
<bpmn:timeDuration>P2DT3H4M</bpmn:timeDuration> <!-- 2 Tage, 3 Stunden, 4 Minuten -->
</bpmn:timerEventDefinition>
</bpmn:intermediateCatchEvent>
Message Events
Коммуникация на основе сообщений:
<bpmn:intermediateCatchEvent id="messageEvent" name="Nachricht empfangen">
<bpmn:messageEventDefinition messageRef="message1"/>
</bpmn:intermediateCatchEvent>
Error Events
Обработка ошибок в процессах:
<bpmn:boundaryEvent id="errorBoundary" attachedToRef="task1">
<bpmn:errorEventDefinition errorRef="error1"/>
</bpmn:boundaryEvent>
BPMN с Camunda
Развёртывание процесса
// Camunda BPMN Prozessdeployment
@Service
public class ProcessDeploymentService {
@Autowired
private RepositoryService repositoryService;
public void deployProcess(String processName, String bpmnFile) {
try (InputStream inputStream = getClass().getResourceAsStream(bpmnFile)) {
Deployment deployment = repositoryService.createDeployment()
.addClassnameResource(processName + ".class")
.addInputStream(processName + ".bpmn", inputStream)
.deploy();
System.out.println("Prozess deployed: " + deployment.getId());
} catch (IOException e) {
throw new RuntimeException("Fehler beim Deployment", e);
}
}
}
Запуск экземпляра процесса
// Camunda Prozessinstanz starten
@Service
public class ProcessInstanceService {
@Autowired
private RuntimeService runtimeService;
public String startProcess(String processKey, Map<String, Object> variables) {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
processKey,
variables
);
return processInstance.getId();
}
public List<Task> getUserTasks(String processInstanceId) {
return taskService.createTaskQuery()
.processInstanceId(processInstanceId)
.list();
}
}
Обработчик задач
// Camunda Task Handler
@Component
public class OrderTaskHandler {
@EventListener
public void handleTaskCreated(TaskCreatedEvent event) {
String taskId = event.getTaskId();
String taskName = event.getTaskName();
if ("Bestellung prüfen".equals(taskName)) {
processOrderTask(taskId);
}
}
private void processOrderTask(String taskId) {
// Business Logik für Bestellprüfung
Map<String, Object> variables = new HashMap<>();
variables.put("orderValid", true);
variables.put("orderAmount", 1000.0);
taskService.complete(taskId, variables);
}
}
Лучшие практики BPMN
1. Правила моделирования процессов
// BPMN Validierungsregeln
public class BPMNValidator {
public ValidationResult validateProcess(Process process) {
ValidationResult result = new ValidationResult();
// Jeder Prozess muss ein Start Event haben
if (!hasStartEvent(process)) {
result.addError("Prozess benötigt mindestens ein Start Event");
}
// Jeder Prozess muss ein End Event haben
if (!hasEndEvent(process)) {
result.addError("Prozess benötigt mindestens ein End Event");
}
// Alle Tasks müssen verbunden sein
if (hasDisconnectedTasks(process)) {
result.addError("Es existieren nicht verbundene Tasks");
}
return result;
}
private boolean hasStartEvent(Process process) {
return process.getFlowElements().stream()
.anyMatch(element -> element instanceof StartEvent);
}
private boolean hasEndEvent(Process process) {
return process.getFlowElements().stream()
.anyMatch(element -> element instanceof EndEvent);
}
}
2. Соглашения по именованию
<!-- Gute Namenskonventionen -->
<bpmn:userTask id="checkOrderTask" name="Bestellung prüfen"/>
<bpmn:exclusiveGateway id="isValidGateway" name="Bestellung gültig?"/>
<bpmn:serviceTask id="sendEmailTask" name="Bestätigung senden"/>
<!-- Schlechte Namenskonventionen -->
<bpmn:userTask id="task1" name="Task 1"/>
<bpmn:exclusiveGateway id="gw1" name="Gateway"/>
3. Оптимизация процессов
// Prozessperformance Analyse
@Service
public class ProcessAnalyticsService {
@Autowired
private HistoryService historyService;
public ProcessMetrics analyzeProcess(String processDefinitionKey) {
List<HistoricProcessInstance> instances = historyService
.createHistoricProcessInstanceQuery()
.processDefinitionKey(processDefinitionKey)
.finished()
.list();
ProcessMetrics metrics = new ProcessMetrics();
metrics.setTotalInstances(instances.size());
metrics.setAverageDuration(calculateAverageDuration(instances));
metrics.setSuccessRate(calculateSuccessRate(instances));
return metrics;
}
private Duration calculateAverageDuration(List<HistoricProcessInstance> instances) {
return instances.stream()
.map(instance -> Duration.between(
instance.getStartTime(),
instance.getEndTime()
))
.reduce(Duration.ZERO, Duration::plus)
.dividedBy(instances.size());
}
}
Инструменты и фреймворки BPMN
1. Camunda Modeler
// Camunda Modeler Plugin Beispiel
const customPlugin = {
id: 'custom-validation-plugin',
init: function(modeler) {
// Custom Validation Rule
modeler.get('validationRules').add('task-name-required', function(element) {
if (element.type === 'bpmn:Task' && !element.name) {
return 'Task muss einen Namen haben';
}
});
// Custom Property Panel
modeler.get('propertiesPanel').registerProvider({
getTabs: function(element) {
if (element.type === 'bpmn:UserTask') {
return {
'custom-task-tab': {
label: 'Custom Task Properties',
entries: [
{
id: 'task-priority',
label: 'Priority',
component: 'textfield',
bindTo: 'customPriority'
}
]
}
};
}
}
});
}
};
2. BPMN.js Integration
// BPMN.js Viewer Integration
import BpmnViewer from 'bpmn-js/lib/Viewer';
class BPMNViewer {
constructor(container) {
this.viewer = new BpmnViewer({
container: container,
width: '100%',
height: '500px'
});
}
async loadDiagram(xml) {
try {
await this.viewer.importXML(xml);
// Zoom to fit
const canvas = this.viewer.get('canvas');
canvas.zoom('fit-viewport');
} catch (err) {
console.error('Error loading BPMN diagram:', err);
}
}
addClickListener(callback) {
this.viewer.on('element.click', function(event) {
const element = event.element;
callback(element);
});
}
}
// Использование
const viewer = new BPMNViewer('#bpmn-container');
viewer.loadDiagram(bpmnXml);
viewer.addClickListener((element) => {
console.log('Clicked element:', element.id, element.name);
});
BPMN на практике
E-commerce процесс оформления заказа
<!-- Комплексный процесс заказа с несколькими участниками -->
<bpmn:definitions>
<!-- Pool: Клиент -->
<bpmn:pool id="customerPool" name="Клиент">
<bpmn:lane id="customerLane" name="Клиент">
<bpmn:userTask id="placeOrder" name="Оформить заказ"/>
<bpmn:userTask id="makePayment" name="Произвести платеж"/>
</bpmn:lane>
</bpmn:pool>
<!-- Pool: Система магазина -->
<bpmn:pool id="shopPool" name="Система магазина">
<bpmn:lane id="orderLane" name="Обработка заказов">
<bpmn:serviceTask id="validateOrder" name="Проверить заказ"/>
<bpmn:serviceTask id="checkInventory" name="Проверить наличие на складе"/>
<bpmn:userTask id="processPayment" name="Обработать платеж"/>
</bpmn:lane>
<bpmn:lane id="warehouseLane" name="Склад">
<bpmn:userTask id="pickItems" name="Подобрать товары"/>
<bpmn:userTask id="packageItems" name="Упаковать"/>
</bpmn:lane>
</bpmn:pool>
<!-- Pool: Служба доставки -->
<bpmn:pool id="deliveryPool" name="Служба доставки">
<bpmn:lane id="deliveryLane" name="Доставка">
<bpmn:serviceTask id="scheduleDelivery" name="Запланировать доставку"/>
<bpmn:userTask id="deliverPackage" name="Доставить посылку"/>
</bpmn:lane>
</bpmn:pool>
<!-- Потоки сообщений между pool'ами -->
<bpmn:messageFlow id="orderMessage" sourceRef="placeOrder" targetRef="validateOrder"/>
<bpmn:messageFlow id="paymentMessage" sourceRef="makePayment" targetRef="processPayment"/>
<bpmn:messageFlow id="deliveryMessage" sourceRef="packageItems" targetRef="scheduleDelivery"/>
</bpmn:definitions>
Процесс согласования с эскалацией
// Процесс согласования с эскалацией
@Service
public class ApprovalProcessService {
public String startApprovalProcess(ApprovalRequest request) {
Map<String, Object> variables = new HashMap<>();
variables.put("requestId", request.getId());
variables.put("amount", request.getAmount());
variables.put("requester", request.getRequester());
variables.put("approvalLevel", determineApprovalLevel(request.getAmount()));
return runtimeService.startProcessInstanceByKey(
"approval-process",
variables
).getId();
}
private String determineApprovalLevel(Double amount) {
if (amount < 1000) return "manager";
if (amount < 10000) return "director";
return "executive";
}
@EventListener
public void handleEscalation(TaskEscalationEvent event) {
String taskId = event.getTaskId();
String escalationLevel = event.getEscalationLevel();
// Передать эскалацию на уровень выше
Map<String, Object> escalationVariables = new HashMap<>();
escalationVariables.put("escalatedFrom", taskId);
escalationVariables.put("escalationReason", event.getReason());
taskService.delegateTask(taskId, escalateLevel + "_approval");
}
}
Подготовка к экзамену по BPMN
Ключевые темы
- Основные элементы BPMN: Events, Activities, Gateways
- Flow Objects: Различные типы и их применение
- Connecting Objects: Sequence Flows, Message Flows, Associations
- Pools и Lanes: Организация процессов и зоны ответственности
- Типы Gateway: Exclusive, Parallel, Inclusive, Complex
- Типы Events: Start, End, Intermediate Events
- Sub-Processes: Embedded и Call Activities
- Data Objects: Представление информации
Типичные экзаменационные задачи
- Анализ процессов: интерпретация BPMN-диаграмм
- Моделирование процессов: представление бизнес-процессов в BPMN
- Применение Gateway: выбор правильных типов шлюзов
- Обработка событий: моделирование процессов, управляемых событиями
- Оптимизация процессов: выявление неэффективности в BPMN-процессах
Концепции для экзамена
// Концепции BPMN, важные для экзамена
public class BPMNExamConcepts {
// 1. Пути процесса и логика шлюзов
public void demonstrateGatewayLogic() {
// Exclusive Gateway: только один путь
// Parallel Gateway: все пути одновременно
// Inclusive Gateway: несколько путей возможны
}
// 2. Управление процессом на основе событий
public void demonstrateEventHandling() {
// Start Events инициируют процессы
// Intermediate Events управляют потоком процесса
// End Events завершают процессы
}
// 3. Поток данных в BPMN
public void demonstrateDataFlow() {
// Data Objects представляют информацию
// Data Stores для постоянных данных
// Associations связывают данные с Activities
}
}
Резюме
BPMN является мощным стандартным инструментом для моделирования процессов, который:
- Стандартизирует единообразное представление процессов
- Визуализирует сложные бизнес-процессы понятным способом
- Автоматизирует прямую интеграцию в системы workflow
- Сотрудничество содействует совместной разработке процессов
- Оптимизирует позволяет систематическое улучшение процессов
Владение BPMN крайне важно для IT-специалистов и бизнес-аналитиков при моделировании, анализе и автоматизации современных бизнес-процессов.
Дополнительные ресурсы:

