How to autowire mongoTemplate into custom type converter?

不问归期 提交于 2019-12-05 18:22:37

ObjectIdToMyObjectConverter is not a spring bean. If you want @Autowired to work, create ObjectIdToMyObjectConverter as Spring bean, like this:

@Bean
public ObjectIdToMyObjectConverter objectIdToMyObjectConverter() {
    return new ObjectIdToMyObjectConverter());
}

and @Autowire it in your configuration.

Following @Savash update

I have not paid enough attention to your configurations.

What you see is happening because you are trying to create MongoTemplate, which depends on CustomConversions, and at the same time CustomConversions depend on MongoTemplate, spring can't and should not do that.

As a solution:

  1. You can create your CustomConversions with ApplicationContextAware, and extract MongoTemplate reference lazily on a first call.
  2. I thought you are using CustomConversions as part of spring-integration or something. If so it does not need to be part of converters for Mongo. If you need it as MongoConverters, you are doing something really strange.

What is exact use case, you need this for?

Following comments:

Do I understand right, that you want MongoTemplate to read object with user reference as User object, and write object with User value as user reference?

I think.

  1. You have a bad data model (you are trying to emulate JOIN operation in your MongoTemplate, which means you are missing something in your data model, and this is not how you should work with mongo).
  2. Just call User explicitly when you need it, don't overload your DB with additional work, you'll have problems with performance
  3. You can use another object, which you'll enrich with current user, as needed
  4. Maybe SQL & ORM like Hibernate is a better approach for you ?
  5. Try Hibernate OGM for your purpose, it might provide functionality, you need (Not sure, though, have not worked with it)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!