How to fix "Field ... required a bean of type ... that could not be found" exception Spring Boot
Asked Answered
P

9

5

I am working with spring boot tutorial from javabrains and everything was clear until putting CrudRepository inside project. Below you can find my main class:

package pl.springBootStarter.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CourseApiDataApplication
{
    public static void main(String args[])
{
    SpringApplication.run(CourseApiDataApplication.class,args);
}
}

Service class:

package pl.springBootStarter.app.topic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TopicService
{
    @Autowired
    private TopicRepository topicRepository;

    private List<Topic> topics =  new ArrayList<>(Arrays.asList(
            new Topic("spring","spring framework", "spring framework dectription"),
            new Topic("sprin","spring framework", "spring framework dectription"),
            new Topic("spri","spring framework", "spring framework dectription")));

    public  List<Topic> getAllTopics()
    {
    //    return topics;
    List<Topic> t = new ArrayList<Topic>();
    topicRepository.findAll().forEach(t::add);
    return t;
    }

    public Topic getTopic (String id)
    {
        return   topics.stream().filter( t -> t.getId().equals(id)).findFirst().get();
    }

    public void addTopic(Topic topic) {
        topicRepository.save(topic);
    }

    public void updateTopic(Topic topic, String id)
    {
        topics.set(topics.indexOf(topics.stream().filter(t-> t.getId().equals(id)).findFirst().get()), topic);
    }

    public void deleteTopic(String id)
    {
        topics.remove(topics.stream().filter(t -> t.getId().equals(id)).findFirst().get());
    }
}

And Repository interface:

package pl.springBootStarter.app.topic;

import org.springframework.data.repository.CrudRepository;

public interface TopicRepository extends CrudRepository<Topic,String>
{

}

When I run the app there is a problem with injection of TopicRepository into topicRepository field in TopicService class. I get following error:

Error starting ApplicationContext. To display the conditions report re-       run your application with 'debug' enabled.
2019-05-01 10:33:52.206 ERROR 6972 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field topicRepository in pl.springBootStarter.app.topic.TopicService required a bean of type 'pl.springBootStarter.app.topic.TopicRepository' that could not be found.

The injection point has the following annotations:
-    @org.springframework.beans.factory.annotation.Autowired(required=true)

What could be the reason that Spring cannot do the autowiring?

Pomfret answered 1/5, 2019 at 8:57 Comment(0)
C
5

Be sure the class is scanned by spring!

(this may help if that's the problem: Intellij Springboot problems on startup).


Optionally you may want to annotate TopicRepository as a @Repository.

@Repository
public interface TopicRepository extends CrudRepository<Topic,String>
{
}

See a demo code here: https://github.com/lealceldeiro/repository-demo

Cloison answered 1/5, 2019 at 9:2 Comment(5)
@Pomfret do you have a repository in which I can take a look? This is supposed to work. I've used it myself a lot of times. Did you make sure spring is detecting the TopicRepository class and registering as a bean??Cloison
In my project there are only 4 classes: CourseApiDataApplication TopicRepository TopicService Topic - the class that contains fields, getters and setters.Pomfret
I am quite new to Spring. How to make sure that spring is detecting TopicRepository class and registering as a bean?Pomfret
I am sure that the problem in my app is that Spring does not find TopicRepository class as a bean. So it does not know what shall be injected in topicRepository field in class TopicService.Pomfret
@Pomfret see this: #52155152 I'm creating a demo for you... give some minutesCloison
S
3

Spring cannot inject bean because it has not been created.

You have to instruct Spring to generate implementation of declared repository interfaces by using @EnableJpaRepositories(basePackages={"pl.springBootStarter.app"}) annotation on any of your configuration classes or class annotated with @SpringBootApplication. That should fix your problem.

Sonorant answered 1/5, 2019 at 9:11 Comment(4)
I put this in my main class and now I have another exception: Field topicRepository in pl.springBootStarter.app.topic.TopicService required a bean named 'entityManagerFactory' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)Pomfret
seems like you haven't configured persistence context, can you post your config file?Sonorant
The solution from @Cloison worked perfectly. I had to put @ComponentScan("packageName") form my package, where I had my Service Repository and Controler classes. Dziękuję za zainteresowanie tematem.Pomfret
I put this, and I messed the routes, appears to me with an error 404Omaomaha
P
3

I got a similar message and I was missing the @Service annotation in the Service class. Simple mistake, posting in case it helps anyone else.

Paralyze answered 3/10, 2020 at 11:10 Comment(0)
M
1

For anybody who was brought here by googling the generic bean error message, but who is actually trying to add a feign client to their Spring Boot application via the @FeignClient annotation on your client interface, none of the above solutions will work for you.

To fix the problem, you need to add the @EnableFeignClients annotation to your Application class, like so:

@SpringBootApplication
// ... (other pre-existing annotations) ...
@EnableFeignClients // <------- THE IMPORTANT ONE
public class Application {
Mario answered 29/9, 2020 at 18:37 Comment(0)
N
1

in service class do: @Autowired(required=false)

Nestor answered 21/2, 2023 at 6:56 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Syllable
E
0

I got a similar message.

the thing was my main package was com.example and the package for other classes was com.xyz

so when I Changed the name of the package of other class to com.example.topic

i.e. finally The main package was com.example and the package for the other class was com.example.topic

A simple mistake, posting in case it helps anyone else.

Exaggeration answered 5/11, 2020 at 6:43 Comment(0)
P
0

In my cases, the necessary configuration from org.springframework.boot.autoconfigure.jdbc. has been excluded at SpringBootApplication, causing relevant bean not added properly. Check your main application java file and see if you can find following configuration in the exclusion list

import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;

@SpringBootApplication(
    exclude = {
        DataSourceAutoConfiguration.class,                      // REMOVE THIS
        DataSourceTransactionManagerAutoConfiguration.class,    // REMOVE THIS
    }
)

and remove them from exclusion list.

Padegs answered 9/10, 2022 at 15:32 Comment(0)
C
0
  1. make sure that your Class has been managed, by adding @Component or @Service or @Controller such kind of annotation
  2. make sure that you have added @ComponentScan (this might be done by Spring or other IoC framework.
  3. make sure that your class path is correct
  4. make sure you have no configuration class to manage your bean, some double database project might use a configuration to manage the different path visiting two different datasource.
Churchly answered 13/6 at 6:22 Comment(0)
R
0

1 the main package is ex: com.demo.project and the remaining package naming should start with com.demo.project 2.For controller package will be like com.demo.project.controller 3.Simlarly for service all well com.demo.project.service

Recitative answered 15/7 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.