Skip to content

DATAREST-524 Invoke validators registered with composite bean names - #2048

Open
laskaridis wants to merge 1 commit into
spring-projects:mainfrom
laskaridis:DATAREST-524
Open

laskaridis wants to merge 1 commit into
spring-projects:mainfrom
laskaridis:DATAREST-524

Conversation

@laskaridis

@laskaridis laskaridis commented Jul 28, 2021 •

Copy link
Copy Markdown

The ValidatingRespositoryEventListener will currently ignore any
validator that has been registered under a composite key consisting of
the event name post-fixed by the model name and the keyword "Validator".
This does not allow executing validator beans registered using the
"@component" or "@bean" annotations, which should be possible according
to the reference guide.

This happens because the code will only look for validators registered
using the event name as a key only. To fix this, I added a second lookup
(if the previous fails) by a composite key name that follows the
semantics described previously.

See: https://docs.spring.io/spring-data/rest/docs/3.5.3/reference/html/#validation

  • You have read the Spring Data contribution guidelines.
  • You use the code formatters provided here and have them applied to your changes. Don’t submit any formatting related changes.
  • You submit test cases (unit or integration tests) that back your changes.
  • You added yourself as author in the headers of the classes you touched. Amend the date range in the Apache license header if needed. For new types, add the license header (copy from another file and set the current year only).

The ValidatingRespositoryEventListener will currently ignore any
validator that has been registered under a composite key consisting of
the event name post-fixed by the model name and the keyword "Validator".
This does not allow executing validator beans registered using the
"@component" or "@bean" annotations, which should be possible according
to the reference guide.

This happens because the code will only look for validators registered
using the event name as a key only. To fix this, I added a second lookup
(if the previous fails) by a composite key name that follows the
semantics described previously.

See: https://docs.spring.io/spring-data/rest/docs/3.5.3/reference/html/#validation
import static org.mockito.Mockito.when;

/**
* Unit tests for {@link ValidatingRepositoryEventListener}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beforeLinkDelete / afterLinkDelete tests have wrong assertions and misleading names

The ValidatingRepositoryEventListener does not override onBeforeLinkDelete or onAfterLinkDelete — those methods are no-ops in the base class. So validators registered under "beforeLinkDelete" or "afterLinkDelete" (or their composite equivalents) will never be invoked. The tests correctly assert assertFalse(validator.isInvoked()), but the test names are deeply misleading:

// Test name says "invokes" but asserts the validator is NOT invoked — this is a lie
public void invokesAfterLinkDeleteValidator_whenValidatorIsRegisteredByCompositeEventName()
public void invokesBeforeLinkDeleteValidator_whenValidatorIsRegisteredByCompositeEventName()
public void invokesBeforeLinkDeleteValidator_whenValidatorIsRegisteredByEventName()

These tests should either:

  • Be renamed to doesNotInvoke... to match the actual assertion, OR
  • The PR should also fix ValidatingRepositoryEventListener to override onBeforeLinkDelete/onAfterLinkDelete and call validate(...) there (which would be the correct behavior, consistent with all other event types).

This is a significant issue — the test names actively mislead future maintainers about expected behavior.

// Allows registering validators by a composite key name consisting of the event name,
// post-fixed by the model name and the keyword "Validator". Useful when registering
// validators as "@Component"s or "@Bean"s (which both require a unique bean name).
if (validators == null || validators.isEmpty()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Composite key lookup silently skips validators when the event name key has validators

The fallback to the composite key only happens when the event-name key returns null or an empty collection:

if (validators == null || validators.isEmpty()) {
    String compositeValidatorKeyName = createCompositeValidatorKeyNameFor(eventName, validationTarget);
    validators = this.validators.get(compositeValidatorKeyName);
}

This means if a user registers validators under both "beforeCreate" and "beforeCreateOrderValidator", only the "beforeCreate" validators will run. This could be surprising. A more robust approach would be to merge both collections rather than treating the composite key as a fallback-only. Consider:

private Collection<Validator> getValidatorsForEvent(String eventName, Object validationTarget) {
    List<Validator> result = new ArrayList<>();
    Collection<Validator> byEvent = this.validators.get(eventName);
    if (byEvent != null) result.addAll(byEvent);
    Collection<Validator> byComposite = this.validators.get(createCompositeValidatorKeyNameFor(eventName, validationTarget));
    if (byComposite != null) result.addAll(byComposite);
    return result;
}

Collection<Validator> validators = this.validators.get(event);
return validators == null ? Collections.<Validator> emptySet() : validators;
private String createCompositeValidatorKeyNameFor(String eventName, Object validationTarget) {
return eventName + validationTarget.getClass().getSimpleName() + "Validator";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The composite key convention is implicit and undocumented in the API

The key format {eventName}{SimpleClassName}Validator is a naming convention that users must know about. There is no Javadoc on addValidator() or setValidators() explaining this convention, and no update to the reference documentation is included in this PR. The reference guide (linked in the PR description) should be updated to explicitly document this composite key pattern.

Also, getSimpleName() is fragile for anonymous/inner classes__

validationTarget.getClass().getSimpleName() returns an empty string for anonymous classes and a $-containing name for non-static inner classes. While these are edge cases, using getSimpleName() without any guard could silently produce a key like "beforeCreate" + "" + "Validator" = "beforeCreateValidator" for an anonymous entity, which would be a confusing key to look up. A comment or guard would be appropriate.

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import static org.junit.Assert.*;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test file uses JUnit 4 + org.junit.Assert instead of the project's established style

The existing test file AnnotatedEventHandlerInvokerUnitTests.java uses:

  • import static org.assertj.core.api.Assertions.*; (AssertJ)
  • No @RunWith annotation (plain JUnit 4 without Mockito runner, or JUnit 5)

The new test file uses:

  • import static org.junit.Assert.*; (JUnit 4 legacy assertions)
  • @RunWith(MockitoJUnitRunner.class) (JUnit 4 runner)
  • 4-space indentation instead of the project's tab-based indentation

The project convention is to use AssertJ (assertThat(...).isTrue(), assertThat(...).isEqualTo(...)) rather than assertTrue/assertEquals. The test should be updated to match.

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.*;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spring Data projects generally prefer explicit imports for clarity. This is a minor style nit but worth flagging for consistency.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: waiting-for-triage An issue we've not yet triaged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants