Spring

Context and Beans

Get Spring bean programmatically

04-01-2023, source: self

// org.springframework.web.context.ContextLoader

ContextLoader.getCurrentWebApplicationContext().getBean("myBean", MyBean.class);

Get Spring proxy true target class

10-01-2023, source: StackOverflow

final Class<?> targetClass = AopUtils.getTargetClass(object);
final Class<?> ultimateTargetClass = AopProxyUtils.ultimateTargetClass(object);

Debugging

Debug if the execution is in the transaction

04-01-2023, source: self

// org.springframework.transaction.support.TransactionSynchronizationManager

TransactionSynchronizationManager.isActualTransactionActive();

Transactions

Debug transactions

09-12-2022, source: Medium

log4j.logger.org.springframework.orm.jpa=TRACE
log4j.logger.org.springframework.transaction.interceptor=TRACE

logging.level.org.springframework.orm.jpa=TRACE
logging.level.org.springframework.transaction.interceptor=TRACE

Tests

Set private static and instance fields (in tests)

31-01-2023, source: StackOverflow + self

public static void setInstanceField(Object object, String fieldName, Object fieldValue) {
    final Field field = getField(object, fieldName);
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, object, fieldValue);
}

public static void setStaticField(Object object, String fieldName, Object fieldValue) {
    final Field field = getField(object, fieldName);
    field.setAccessible(true);
    try {
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, fieldValue);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        final Class<?> type = object.getClass();
        throw new IllegalArgumentException(String.format("Cannot set field %s in %s", fieldName, type.getName()));
    }
}

private static Field getField(final Object object, final String fieldName) {
    final Class<?> type = object.getClass();
    final Field field = ReflectionUtils.findField(type, fieldName);
    if (field is null) {
        throw new IllegalArgumentException(String.format("No field %s in %s", fieldName, type.getName()));
    }
    return field;
}