Search code examples
spring-bootjavabeans

How to create Bean in SpringBoot


I have a MongoUserUrlRepository from which I have to create Bean.

Code looks like this:

public class MongoUserUrlRepository extends AbstractRepositoryImpl<MongoUserId, UserUrl> implements UserUrlRepository {

    public MongoUserUrlRepository(MongoClient mongoClient, String db, String collection) {
        super(
                mongoClient,
                db,
                collection,
                MongoUserId::asString,
                id -> MongoUserId.mongoUserId((String) id)
        );
    }

    @Override
    protected Document toDocument(UserUrl uv) {
        final Document d = new Document();

        uv.url.ifPresent(url -> d.put("url",url));
        d.put("version", uv.version);
        d.put("requestedDate", toDate(uv.requestedDate));
        d.put("state", uv.state.name());
        return d;
    }

    @Override
    protected UserUrl fromDocument(Document d) {
        return UserUrl.userUrl(
                idFrom(d),
                d.getString("url"),
                d.getLong("version"),
                toInstant(d.getDate("requestedDate")),
                State.valueOf(d.getString("state"))
        );
    }
}

I have tried to create Bean like this:

@Bean
public UserUrlRepository getUserUrlRepository(MongoClient mongoClient, String dataBase, String collection){
    return new MongoUserUrlRepository(mongoClient, dataBase, collection);
}

But mongoClient, dataBase, collection is not recognized.

What am I missing?


Solution

  • You should first define a MongoClient bean and instruct the container where to find the 2 strings dataBase and collection For the Strings you can define them as property and use @Value annotation to inject them.

    Edit code example:

    @Configuration
    public class Config {
    
      @Bean 
      public MongoClient mongoClient(){ // This bean should exist, it will be used and injected in the getUserUrlRepository(..) method
          return new MongoClient();
      }
    
      @Bean
      public UserUrlRepository getUserUrlRepository(MongoClient mongoClient, @Value("${database.property}") String dataBase, @Value("${collection.property}") String collection){
          return new MongoUserUrlRepository(mongoClient, dataBase, collection);
      }
    }
    

    And sure, you should have defined database.property and collection.property in your application.properties or somewhere else.