简体   繁体   中英

Spring Mongo DB with Annotation based configurations

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.

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"));

    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM