简体   繁体   中英

Getting the error : Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException

I am new to spring and I wanted to communicate with mongodb via spring. I tried and tested the following code on SPRING TOOL SUITE but I am getting the following error:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hello.PersonRepository] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
at hello.Runhere.main(Runhere.java:19)

Kindly tell me where is the problem.

Here is Person.java class

package hello;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Person {

@Id
private String personId;

private String name;
private int age;

public Person(String name, int age) {
    this.name = name;
    this.age = age;
    }

public String getPersonId() {
    return personId;
    }

public void setPersonId(final String personId) {
    this.personId = personId;
    }

public String getName() {
    return name;
    }

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

public int getAge() {
    return age;
    }

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

@Override
public String toString() {
    return "Person [id=" + personId + ", name=" + name + ", age=" + age
            + "]";
    }

}

Here is my PersonRepository.java file

package hello;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

@Repository
public class PersonRepository {


@Autowired
MongoTemplate mongoTemplate;

public void countUnderAge() {
    List<Person> results = null;

    Query query = new Query();
    Criteria criteria = new Criteria();
    criteria = criteria.and("age").lte(21);

    query.addCriteria(criteria);
    results = mongoTemplate.find(query, Person.class);

    System.out.println(results.size());
}

public void countAllPersons() {
    List<Person> results = mongoTemplate.findAll(Person.class);
    System.out.println("The total number of players " + results.size());
}

public void insertPersonWithNameAayushAndRandomAge() {

    double age = Math.ceil(Math.random() * 100);
    Person p = new Person("Aayush", (int) age);

    mongoTemplate.insert(p);
}

public void createPersonCollection() {
    if (!mongoTemplate.collectionExists(Person.class)) {
        mongoTemplate.createCollection(Person.class);
    }
}

public void dropPersonCollection() {
    if (mongoTemplate.collectionExists(Person.class)) {
        mongoTemplate.dropCollection(Person.class);
    }
}
}

Here is my springconfig.java file:

package hello;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import com.mongodb.Mongo;

@Configuration
@EnableMongoRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class springconfig extends AbstractMongoConfiguration {

@Override
protected String getDatabaseName() {
    return "demo";
}

@SuppressWarnings("deprecation")
@Override
public Mongo mongo() throws Exception {
    return new Mongo();
}

}

Here is my class which contains the main method :

package hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Runhere {
public static void main(String[] args) {

    @SuppressWarnings("resource")
    ApplicationContext context = new AnnotationConfigApplicationContext(springconfig.class);

    PersonRepository personRepository = context.getBean(PersonRepository.class);

    personRepository.dropPersonCollection();
    personRepository.createPersonCollection();

    for (int i = 0; i < 10000; i++) {
        personRepository.insertPersonWithNameAayushAndRandomAge();
    }

    personRepository.countAllPersons();
    personRepository.countUnderAge();
}
}

And finally here is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>integration_with_mongo</name>
<description>Demo project for Spring Boot</description>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>demo.IntegrationWithMongoApplication</start-class>
    <java.version>1.7</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>

    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>

    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-rest-repository</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-rest-webmvc</artifactId>

    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>

    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.webflow</groupId>
        <artifactId>spring-webflow</artifactId>
        <version>2.4.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>


</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

try to add bean in the application config.xml

 <mvc:resources mapping="" location="" /> 


<bean id="PersonRepository" class="(complete package path)hello.PersonRepository" /> 

SpringBoot - In hope it will help any SpringBoot developer

This error mostly hits when the bean you are calling from another package.

Specifically for Spring boot , you can try an annotation for it, to scan the component you want to get bean of it.

@ComponentScan("your package") 

place the @Componentscan annotation in the main class where you are getting the bean.

Example

@ComponentScan("com.spring.crud.controller")
public class SpringCrudApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringCrudApplication.class, args);
        
        HomeController bean1 = context.getBean(HomeController.class);
        System.out.println(bean1.HomePage());
    }

}

so, in the above example I am taking controller bean which I created in the package of com.spring.crud.controller

if you are interested in explanation see this article: https://baidar-sabaoon.medium.com/how-to-handle-nosuchbeandefinitionexception-in-spring-boot-7255170d702c

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