2
donuts
4y

How does Spring Boot/Data create a MongoClient/Template Bean to a **remote** database that requires password, certs, other configs?

These would be set in application properties but how does it get translated to the Beans?

I went through a lot of examples is like @Autowired MongoClient client

And then they just use it.

And I'm like wtf?

Comments
  • 1
    It should get translated to the beans automatically if the classpath etc. is set up correctly - you just set `spring.data.mongodb.uri` for instance in application.properties, then off you go.

    If you want to do it manually, I think you can just return something like return new SimpleMongoDbFactory(new MongoClientURI(uri)) as a bean, but there's rarely a need to do that.
  • 1
    @AlmondSauce so the instation is hidden in some Spring code. Any guess which class, I believe Spring is open source.

    The thing is we need to pass in the params seperatly, can't just use a uri. There's like password, ssl certs path. Some are in properties, password is an env var, etc.

    I think it needs an @EnabkeMongRepository in the main class? But where the code that actually does the magic?
  • 0
    In our code we tend to have config classes where we define all those kinds of beans.
    Just have a bean definition of type MongoClient and return your instance in there, passing in uri/creds from your properties.
  • 0
    @LLAMS but that's manual? Passing in. How to use Spring Data's AutoConfig? That seems to be what all the online examples do but none actually explain how it works.

    Most just go from @EnabkeMongoRepository to using a @Repository class.

    I want the MongoClient, Template bean though...
  • 1
    @donuts Not sure where it's instantiated I'm afraid, I've never dealt with Spring data MongoDB specifically. You can grab the source here and search though if you want to find out (https://github.com/spring-projects/...).
  • 0
    Spring looks if a bean is already defined and if it isn't it tries to create one.

    This also means you can inject your own beans to override the default one with ease

    Something like this *might* hold the answer, but Im not at a PC right now, check out if the client factory or the constructor holds what you need:

    https://docs.spring.io/spring-data/...
  • 0
    @Hazarth sorta figured it out but the default needs a crazy long uri in the yaml in order to support replica sets.

    Seems it's connected but but the queries don't seem to be returning anything...

    Trying to use reactive but it returns a Flux? That isn't an error but doesn't have a value...

    But sure how that's possible. Or maybe I'm missing a param for seeing it to the right db... Can't figure it out..

    And it's the weekend so I think I'll just call it quits for now
Add Comment