Category Archives: java

Working with meta-annotations

Spring framework has the very nice feature of supporting meta-annotations. I wanted to implement the same thing for jTransfo.

The idea is that you can write a custom annotation to replace one or more other annotations. For example in jTransfo, you can define a @ReadOnly annotation which replaces @MappedBy(readOnly = true).

You can define the custom annotation like this:

@MappedBy(readOnly = true)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Documented
public @interface ReadOnly {
 
}

Note that this annotation can itself also be used as meta-annotation thanks to the ANNOTATION_TYPE target.

To check whether an annotation exists on a field or method, you need to read through the chain. This can be done using this code:

    /**
     * Get the annotations of given type which are available on the annotated element. Considers both the annotations
     * on the element and the meta-annotations (annotations on the annotations).
     * The result is given in no specific order
     *
     * @param element annotated element
     * @param annotation annotation to find
     * @param <T> annotation type
     * @return
     */
    public <T extends Annotation> List<T> getAnnotationWithMeta(AnnotatedElement element, Class<T> annotation) {
        return (List) Stream.of(element.getDeclaredAnnotations())
                .flatMap(this::addMetaAnnotations)
                .filter(a -> annotation.isAssignableFrom(a.annotationType()))
                .collect(Collectors.toList());
    }
 
    private Stream<Annotation> addMetaAnnotations(Annotation a) {
        Set<Annotation> res = new HashSet<>();
        addMetaAnnotations(res, a);
        return res.stream();
    }
 
    private void addMetaAnnotations(Set<Annotation> set, Annotation annotation) {
        if (set.add(annotation)) { // set is needed or continues infinitely
            for (Annotation meta : annotation.annotationType().getDeclaredAnnotations()) {
                addMetaAnnotations(set, meta);
            }
        }
    }

Transaction management with Spring in Activiti

You can make sure that Activiti uses the transaction manager defined in Spring using the “transactionManagement” property on the SpringProcessEngineConfiguration class.

This works but behaves different from how Hibernate/JPA behave.

When you explicitly create your transaction boundaries (using TransactionTemplate or @Transactional annotations), these are simple used as expected.

However if you do not define the transaction boundaries, Hibernate/JPA will throw an exception indication that a transaction needs to be active while Activiti will simply create a transaction, more or less working in autocommit mode.

You can assure that Activiti has similar behaviour as Hibernate/JPA by using a custom SpringProcessEngineConfiguration class. Unfortunately, this does not work in all cases. When you use the jobExecutor (so jobExecutorActive needs to be false). You also need to assure that the conversion does not occur during auto deploy of resources.

public class MySpringProcessEngineConfiguration extends SpringProcessEngineConfiguration {
 
    private DcSpringTransactionInterceptor txInterceptor;
 
    @Override
    protected CommandInterceptor createTransactionInterceptor() {
        if (transactionManager == null) {
            throw new ActivitiException("transactionManager is required property for SpringProcessEngineConfiguration, use "
                    + StandaloneProcessEngineConfiguration.class.getName() + " otherwise");
        }
 
        txInterceptor = new DcSpringTransactionInterceptor(transactionManager);
        return txInterceptor;
    }
 
    @Override
    public ProcessEngine buildProcessEngine() {
        if (null != txInterceptor) {
            txInterceptor.setConvertRequiredToMandatory(false);
        }
        ProcessEngine processEngine = super.buildProcessEngine();
        ProcessEngines.setInitialized(true);
        autoDeployResources(processEngine);
        if (null != txInterceptor) {
            txInterceptor.setConvertRequiredToMandatory(true);
        }
        return processEngine;
    }
 
}

The actual work is done in the MySpringTransactionInterceptor which converts REQUIRED transaction propagation to MANDATORY.

@Slf4j
class MySpringTransactionInterceptor extends SpringTransactionInterceptor {
 
    @Setter
    private boolean convertRequiredToMandatory;
 
    /**
     * Constructor.
     *
     * @param transactionManager transaction manager
     */
    DcSpringTransactionInterceptor(PlatformTransactionManager transactionManager) {
        super(transactionManager);
    }
 
    @Override
    public <T> T execute(final CommandConfig config, final Command<T> command) {
        log.debug("Running command with propagation {}", config.getTransactionPropagation());
 
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(getPropagation(config));
 
        return transactionTemplate.execute((status) -> next.execute(config, command));
    }
 
    private int getPropagation(CommandConfig config) {
        switch (config.getTransactionPropagation()) {
            case NOT_SUPPORTED:
                return TransactionTemplate.PROPAGATION_NOT_SUPPORTED;
            case REQUIRED:
                if (convertRequiredToMandatory) {
                    return TransactionTemplate.PROPAGATION_MANDATORY; // omgezet naar mandatory, tx handling moet expliciet gebeuren
                } else {
                    return TransactionTemplate.PROPAGATION_REQUIRED;
                }
            case REQUIRES_NEW:
                return TransactionTemplate.PROPAGATION_REQUIRES_NEW;
            default:
                throw new ActivitiIllegalArgumentException("Unsupported transaction propagation: " + config.getTransactionPropagation());
        }
    }
 
}

Transactional annotation on a Spring service method not picked up

I spent several hours trying to hunt down why a @Transactional annotation on a method was not being picked up. It was picked up on various other method, but not on this particalar service which only contains one method.

@Component
public class SomeHelper {
 
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    protected ReturnType doSomething(String paramater) {
        // handling code
    }
 
}

There are also some autowired components in there which were working.

Several hours later, I found it.

protected

Apparently the annotation is only applied to public methods.