spring-data-mongodb icon indicating copy to clipboard operation
spring-data-mongodb copied to clipboard

Java config equivalent of `mapping-context-ref` in `<mongo:auditing />`

Open LeeU1911 opened this issue 2 years ago • 1 comments

Hey everyone, I couldn't seem to find an official answer on how to reference a custom mapping context when using annotation @EnableMongoAuditing. For XML configuration, official docs specified

<mongo:auditing mapping-context-ref="customMappingContext" auditor-aware-ref="yourAuditorAwareImpl"/>

But equivalent Java config doesn't seem to have mapping-context-ref if I'm not wrong

@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(MongoAuditingRegistrar.class)
public @interface EnableMongoAuditing {

	/**
	 * Configures the {@link AuditorAware} bean to be used to lookup the current principal.
	 *
	 * @return empty {@link String} by default.
	 */
	String auditorAwareRef() default "";

	/**
	 * Configures whether the creation and modification dates are set. Defaults to {@literal true}.
	 *
	 * @return {@literal true} by default.
	 */
	boolean setDates() default true;

	/**
	 * Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}.
	 *
	 * @return {@literal true} by default.
	 */
	boolean modifyOnCreate() default true;

	/**
	 * Configures a {@link DateTimeProvider} bean name that allows customizing the {@link org.joda.time.DateTime} to be
	 * used for setting creation and modification dates.
	 *
	 * @return empty {@link String} by default.
	 */
	String dateTimeProviderRef() default "";
}

There is one StackOverflow answer suggests that by autowiring the mapping context in the same config class annotated with @EnabledMongoAuditing, it'll be picked up automatically as in

@Configuration
@EnableMongoAuditing
class Config {
  @Autowired
  MongoContext customMongoContext;

  @Bean
  public AuditorAware<AuditableUser> myAuditorProvider() {
      return new AuditorAwareImpl();
  }
}

In my case, I've tried without much success where IsNewAwareAuditingHandler bean is created with default mongo mapping context.

Background: My application has multiple datasources, so we have multiple custom mapping contexts/mongo factories/mongo templates/etc. When I upgraded to spring-data-mongodb 3.3.2, I faced an issue where an entity from second database is not recognized by mapping context during auditing logic.

org.springframework.data.mapping.MappingException: Unknown persistent entity ...

Debug shows the mapping context being used contains entities of the first database instead. I didn't have this issue on 2.2.12.RELEASE

It'll be very appreciated if someone can shed a light on this

LeeU1911 avatar Mar 25 '22 15:03 LeeU1911

Hey @christophstrobl, thanks for assigning this to yourself. Do you know if it's already possible to do this via Java config, or it'd need some change?

LeeU1911 avatar Apr 04 '22 13:04 LeeU1911