0

I am learning Spring Boot and I am trying to make a very simple app that fetches data from Mongo DB by using Dynamic Queries. I am using Intellij as my IDE.

FILE: application.properties (inside resource folder)

spring.mongo.host=127.0.0.1
spring.mongo.port=27017
spring.mongo.databaseName=spring

FILE: person.java

@Document (collection = "person")
public class Person {
    @Id
    String id;
    int age;
    String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

FILE: MyRepo.java

@Repository
public interface MyRepo extends PagingAndSortingRepository<Person, String> {
    public List<Person> findAllByName(String name);
}

FILE: Config.java

@Configuration
@EnableMongoRepositories(basePackages = {"mongo.customQueries"})
public class Config {

}

FILE: Main.java

public class Main {
    @Autowired
    public static MyRepo myRepo;
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        MyRepo myRepo = context.getBean(MyRepo.class);
        System.out.println(myRepo.findAllByName("Avishek"));

    }
}

When I run the project, I get an error

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [mongo.customQueries.MyRepo] is defined

What is it that I am missing here? Why is my MyRepo bean not created as most of the examples in net are doing so.

halfer
  • 19,824
  • 17
  • 99
  • 186
Juvenik
  • 900
  • 1
  • 8
  • 26

2 Answers2

0

The problem is you want to annotation the MyRepo in the Main class, please remove it as below:

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        MyRepo myRepo = context.getBean(MyRepo.class);
        System.out.println(myRepo.findAllByName("Avishek"));

    }
}
Liping Huang
  • 4,378
  • 4
  • 29
  • 46
0

If someone could just give me a simple example to run Dynamic Queries in Spring boot with mongo. Some examples similar to that of above. Or how can I make the above example correct.

You can see working example here. And find explanations here.

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192