228

I am getting the following error:

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

Description:

Parameter 0 of method setApplicant in webService.controller.RequestController required a bean of type 'com.service.applicant.Applicant' that could not be found.


Action:

Consider defining a bean of type 'com.service.applicant.Applicant' in your configuration.

I have never seen this error before but it's odd that the @Autowire is not working. Here is the project structure:

Applicant Interface

public interface Applicant {
    
    TApplicant findBySSN(String ssn) throws ServletException;
    
    void deleteByssn(String ssn) throws ServletException;
    
    void createApplicant(TApplicant tApplicant) throws ServletException;
    
    void updateApplicant(TApplicant tApplicant) throws ServletException;
    
    List<TApplicant> getAllApplicants() throws ServletException;
}

ApplicantImpl

@Service
@Transactional
public class ApplicantImpl implements Applicant {

private static Log log = LogFactory.getLog(ApplicantImpl.class);
    
    private TApplicantRepository applicantRepo;

@Override
    public List<TApplicant> getAllApplicants() throws ServletException {
        
        List<TApplicant> applicantList = applicantRepo.findAll();
        
        return applicantList;
    }
}

Now I should be able to just Autowire Applicant and be able to access, however in this case it is not working when I call it in my @RestController:

@RestController
public class RequestController extends LoggingAware {
    
    private Applicant applicant;
    
    @Autowired
    public void setApplicant(Applicant applicant){
        this.applicant = applicant;
    }
    
    @RequestMapping(value="/", method = RequestMethod.GET)
    public String helloWorld() {
        
        try {
            List<TApplicant> applicantList = applicant.getAllApplicants();
            
            for (TApplicant tApplicant : applicantList){
                System.out.println("Name: "+tApplicant.getIndivName()+" SSN "+tApplicant.getIndSsn());
            }
            
            return "home";
        }
        catch (ServletException e) {
            e.printStackTrace();
        }
        
        return "error";
    }
    
}

------------------------UPDATE 1-----------------------

I added

@SpringBootApplication
@ComponentScan("module-service")
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

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

}

and the error went away but nothing happened. However when I commented out everything dealing with Applicant in the RestController prior to adding @ComponentScan() I was able to return a string the UI, thus meaning my RestController was working, now it is being skipped. I got an ugly Whitelabel Error Page now.

---------------------UPDATE 2------------------------------

I added the base package of the bean it was complaining about. Error reads:

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

Description:

Parameter 0 of method setApplicantRepo in com.service.applicant.ApplicantImpl required a bean of type 'com.delivery.service.request.repository.TApplicantRepository' that could not be found.


Action:

Consider defining a bean of type 'com.delivery.request.request.repository.TApplicantRepository' in your configuration.

I added @ComponentScan

@SpringBootApplication
@ComponentScan({"com.delivery.service","com.delivery.request"})
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

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

}

----------------------------Update 3----------------------

adding:

@SpringBootApplication
@ComponentScan("com")
public class WebServiceApplication extends SpringBootServletInitializer {

still is complaining about my ApplicantImpl class which @Autowires my repo TApplicantRepository into it.

Naseer Mohammad
  • 389
  • 4
  • 14
Mike3355
  • 11,305
  • 24
  • 96
  • 184
  • Where is your application context file? If you don't have one, you should consider to give *Spring* some hint with annotations like *@ComponentScan* to make all beans available. – Mario Santini Nov 02 '16 at 15:53
  • @MarioSantini please see update 1 – Mike3355 Nov 02 '16 at 16:03
  • I assume after each update there were changes in the errors? If possible, do post your project structure, and the error logs/stacktrace in each case.. Its better to know "Why" those error occured, rather than a "something" made the error go away. Will be helpful for others who come across a similar issue as well. – ameenhere Nov 02 '16 at 22:55

54 Answers54

336

It might be because the project has been broken down into different modules.

@SpringBootApplication
@ComponentScan({"com.delivery.request"})
@EntityScan("com.delivery.domain")
@EnableJpaRepositories("com.delivery.repository")
public class WebServiceApplication extends SpringBootServletInitializer {
Aakash K T
  • 47
  • 8
Mike3355
  • 11,305
  • 24
  • 96
  • 184
  • 11
    Cool. My project is divided by a number of modules. ComponentScan solved my issue! – kholofelo Maloma Mar 24 '17 at 11:19
  • ComponentScan annotation resolve my issue but @EnableAutoConfiguration doesn't – jpl Nov 28 '17 at 15:29
  • In fact EnableAutoConfiguration implicitly defines a base “search package” for certain items and using a root package also allows the ComponentScan annotation to be used without needing to specify a basePackage attribute. And @SpringBootApplication annotation could be used if your main class is in the root package – jpl Nov 28 '17 at 15:36
  • 2
    This solution helped me with this error in version 2.0.4 – manu muraleedharan Sep 04 '18 at 12:43
  • 6
    Yes, it is due to the fact that the project has been broken down into different modules. `@EntityScan` and `@EnableJpaRepositories` with the right package names worked for me. – Adi Sivasankaran Oct 15 '18 at 02:51
  • Thanks, this solved my problem. Although IntelliJ says that the ComponentScan declaration is redundant because SpringBootApplication already applies it. Weird... – Jan Horčička Apr 19 '20 at 09:46
  • yup removing the `@EntityScan` solved the issue, ty – user9869932 Nov 14 '20 at 02:56
  • This works, if you have the file from some other module – CodingBee Sep 14 '21 at 08:30
  • had the same issue when I was trying to run the test classes that out of the main package. after adding the component scan, it worked – Sumeet Vishwas Oct 03 '22 at 04:59
  • For me @ ComponentScan helped, but had to add multiple other packages for the nested dependencies. Realized later that I had also made use of @ Profile for my class. Ensuring I had added this profile to the VM args for program run solved the issue and I didn't need @ ComponentScan post that. – VinjaNinja Jan 23 '23 at 10:50
167

There is a chance...
You might be missing @Service, @Repository or @Component annotation on your respective implementation classes.

Kostanos
  • 9,615
  • 4
  • 51
  • 65
CodeWorld
  • 2,017
  • 1
  • 11
  • 21
  • 10
    This should be the accepted answer, simple and to the point fix. Thank you. – nightfury Mar 10 '19 at 17:00
  • 1
    Thank you, I was missing @Repository annotation – sergodeeva Apr 11 '20 at 12:09
  • 3
    Yeah this should be the answer. Above answers are simply assuming that the scan failed, which is wrong. – Sumit Badsara Jun 15 '20 at 20:31
  • 4
    Thank you! @Service was missing on mine! – spacing Feb 18 '21 at 15:32
  • 2
    Perfect, thank you! I was going through a few tutorials to create a REST api and they used services to implement the various functions, but not one of them annotated the interface with `@Service` . So here's a solution if someone else has the same problem! – need_to_know_now Feb 23 '21 at 17:49
  • I forgot to use @Service annotation on my service class. – Sash_KP Jun 13 '21 at 11:05
  • I have all these anotations and still the same error, stop copy and paste solutions wothout testing – fsalazar_sch May 23 '22 at 15:46
  • @fsalazar_sch Sorry if it hurts ur feelings, I would like to know from where this solution is copied ? And if it didn't work out for u, plz check another answers in the thread. – CodeWorld May 24 '22 at 11:12
  • In my case there were 2 beans with the same name, for different objects: `@Bean public Foo beanName() ` and `@Bean public SomethingElse beanName()` – tonyfarney Aug 26 '22 at 00:02
65

Your Applicant class is not scanned it seems. By default all packages starting with the root as the class where you have put @SpringBootApplication will be scanned.

suppose your main class "WebServiceApplication" is in "com.service.something", then all components that fall under "com.service.something" is scanned, and "com.service.applicant" will not be scanned.

You can either restructure your packages such that "WebServiceApplication" falls under a root package and all other components becomes part of that root package. Or you can include @SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"}) etc such that "ALL" components are scanned and initialized in the spring container.

Update based on comment

If you have multiple modules that are being managed by maven/gradle, all spring needs is the package to scan. You tell spring to scan "com.module1" and you have another module which has its root package name as "com.module2", those components wont be scanned. You can even tell spring to scan "com" which will then scan all components in "com.module1." and "com.module2."

Vasu
  • 21,832
  • 11
  • 51
  • 67
ameenhere
  • 2,203
  • 21
  • 36
  • My project is structure is different modules. For example the services will have its own module and `build.gradle`. Those `build.gradle` module names are added to the `dependencies` of the module with the main method. Therefore when you seen `@ComponentScan("module-service")` that's what I thought would work. However inside `module-service` has one package. So my question what would that look like? Do I just name the package name or the module name or somehow both? – Mike3355 Nov 02 '16 at 17:11
  • It doesnt matter if the packages fall into different modules. The packages in which the components should be scanned should be specified to spring. You can give all the "root" package names of all your modules in "scanBasePackages" attribute.. And its all "packages" that has to be mentioned,not modules. – ameenhere Nov 02 '16 at 17:14
  • Did what you said and, the error went away but to only complain about yet another package. Naturally I added it to the list but it will not go away. I implemented it like this: `@SpringBootApplication(scanBasePackages= {"com.delivery.service","com.delivery.request"})` – Mike3355 Nov 02 '16 at 17:58
  • I just did `@SpringBootApplication(scanBasePackages= "com")` and it is complaining about the JPA repository. Thank you very much. I did not know spring would scan all packages that start with "com" if you do the above. – Mike3355 Nov 02 '16 at 18:21
32

Basically this happens when you have your Class Application in "another package". For example:

com.server
 - Applicacion.class (<--this class have @ComponentScan)
com.server.config
 - MongoConfig.class 
com.server.repository
 - UserRepository

I solve the problem with this in the Application.class

@SpringBootApplication
@ComponentScan ({"com.server", "com.server.config"})
@EnableMongoRepositories ("com.server.repository") // this fix the problem

Another less elegant way is to: put all the configuration classes in the same package.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Carlos Marcano
  • 610
  • 6
  • 6
  • 5
    Infact, you do not need to specify `@ComponentScan` in the above scenario. Because your `Application.class` (which has the `@SpringBootApplication` annotation) is placed in `com.server` which is anyway the root for both `com.server.config` as well as `com.server.repository` . – ameenhere Apr 27 '17 at 18:17
  • @Ameen.MThat's my exact question, Why it is still cannot solve and why does it require explicit scan for the mongo repos using `@EnableMongoRepositories` ? – Karthikeyan Nov 08 '18 at 14:17
24

In my case I had a terrible mistake. I put @Service up to the service interface.

To fix it, I put @Service on the implementation of service file and it worked for me.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Mehdi Fallahi
  • 343
  • 2
  • 5
11

If a bean is in the same package in which it is @Autowired, then it will never cause such an issue. However, beans are not accessible from different packages by default. To fix this issue follow these steps :

  1. Import following in your main class:
    import org.springframework.context.annotation.ComponentScan;
  2. add annotation over your main class :
@ComponentScan(basePackages = {"your.company.domain.package"})
public class SpringExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringExampleApplication.class, args);
    }
}
Adam Michalak
  • 155
  • 1
  • 8
ASHWANI PANDEY
  • 151
  • 1
  • 4
8

Important:

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 {

Side note: adding a @ComponentScan(...) beneath @SpringBootApplication is redundant, and your IDE should flag it as such (IntelliJ IDEA does, at least).

eriegz
  • 335
  • 3
  • 10
  • 2
    Thanks, this was exactly the issue I was having with the @FeignClient not getting recognized. But adding the EnableFeignClients solved the problem. thanks! – Amir Nov 09 '20 at 22:36
  • In my case I had to specify the package location in @EnableFeignClients: For example **@EnableFeignClients ("com.myapp.client")** – Flavio Oliva Jun 22 '21 at 12:24
6

This can also happen if you are using Lombok and you add the @RequiredArgsConstructor and @NonNull for fields but some of your fields are not to be injected in the constructor. This is only one of the possibilities to get the the same error.

parameter 0 required a bean of type MissingBeanName that could not be found

In my case the error told me what Controller the problem was in, after removing @NonNull the application started fine

Dherik
  • 17,757
  • 11
  • 115
  • 164
Dawid Gorczyca
  • 941
  • 10
  • 9
  • This was my error as well except with an `@AllArgsConstructor` removing the annotation and letting java create an empty constructor let spring instantiate the object correctly and inject dependencies. – Christian Bartram Aug 23 '20 at 15:26
6

In my case these two options worked.

  1. in //@ComponentScan ({"myapp", "myapp.resources","myapp.services"}) include also the package which holds the Application.class in the list, or

  2. Simply add @EnableAutoConfiguration; it automatically recognizes all the spring beans.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Sriharsha g.r.v
  • 456
  • 5
  • 13
6

I faced with familiar problem in my Maven multi-module project with Spring Boot 2. The problem was related to naming of my packages in sub Maven modules.

@SpringBootApplication incapsulate a lots of component like - @ComponentScan, @EnableAutoConfiguration, jpa-repositories, json-serialization and so on. And he places @ComponentScan in com.*******.space package. This part of packages com.*******.space must be common for all modules.

For fixing it:

  1. You should rename all module packages. Other words you had to have in all packages in all Maven modules - the same parent part. For example - com.*******.space
  2. Also you have to move your entry point to this package - com.*******.space
alexis_dia
  • 156
  • 3
  • 13
5

I think you can make it simplified by annotating your repository with @Repository, then it will be enabled automatically by Spring Framework.

Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
4

It worked for me after adding below annotation in application:

@ComponentScan({"com.seic.deliveryautomation.mapper"})

I was getting the below error:

"parameter 1 of constructor in required a bean of type mapper that could not be found:

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
Love Kumar
  • 41
  • 1
4

Moving the Springbootapplication(application.java) file to another package resolved the issue for me. Keep it separate from the controllers and repositories.

Chakri
  • 139
  • 1
  • 11
  • also mention componentscan(basePackages={" "," "} to consider the packages where your controllers are present – Chakri Sep 15 '20 at 06:50
3

In my case this error appear because my import was wrong, for example, using spring, the import automatically appear:

import org.jvnet.hk2.annotations.Service;

but i needed:

import org.springframework.stereotype.Service;
3

I faced the same issue. Mongo DB repository was identified by Spring boot, but it was not creating Bean for a repository interface that extended the mongo repository.

The issue in my case was incorrect version specification in maven pom for "spring + mango". I have changed the artifact's group id and it all worked like magic. no annotations needed as spring boot took care of everything.

During my problem resolution, I was all over web searching for solutions and realized that this problem is actually project configuration related, anyone facing this issue should first check their project setup and enable debug from spring to get more details on failure and pay close attention to where exactly in the process, the creation has failed.

2

I sought online for an answer but it seems there is no one proper solution to my case: At the very beginning, everything works well as follows:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
}

Then I am trying to add a map to cache something and it becomes this:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
    Map<String, String> testMap;
}

Boom!

Description:

Parameter 4 of constructor in *.GroupService required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

I removed the @AllArgsConstructor(onConstructor = @__(@Autowired)) and add @Autowired for each repository and service except the Map<String, String>. It just works as before.

@Slf4j
@Service
public class SecurityGroupService {
    @Autowired
    private Repository repository;
    @Autowired
    private Service service;
    Map<String, String> testMap;
}

Hope this might be helpful.

Hearen
  • 7,420
  • 4
  • 53
  • 63
2

This can happen if the @Service class is marked abstract.

Ariel
  • 25,995
  • 5
  • 59
  • 69
2

@Configuration annotation will just solve the error

2

You'll also get this error if you accidentally define the same bean in two different classes. That happened to me. The error message was misleading. When I removed the extra bean, the issue was resolved.

Ross Mills
  • 111
  • 1
  • 3
2

My error was that I had included:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

instead of:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
B. Go
  • 1,436
  • 4
  • 15
  • 22
2

It might help somebody. I had the same problem, same error message, same everything. I tried solutions from other answers, didn't help until I realised that the bean I am using has the same name as the one that is actually been autowired. It happened in the midst of refactor, thus I had to rename the class, which resulted positively. Cheers

Staxx
  • 23
  • 3
2

Try configuring the project structure as given below:

Put all the repo, service, packages in the child package of the main package:

package com.leisure.moviemax;  //Parent package
        
@SpringBootApplication
@PropertySource(value={"classpath:conf.properties"})
    
public class MoviemaxApplication implements CommandLineRunner {
        
package com.leisure.moviemax.repo; //child package

@Repository
public interface UsrRepository extends JpaRepository<UserEntity,String> {
Barani r
  • 2,119
  • 1
  • 25
  • 24
2

This error message also pops up when you fail to annotate the Entity classes associated with your bean with the @Entity Annotation.

My ComponentScan worked fine but this popped up for the @repository interface:

@Repository
public interface ExpenseReportAuditRepository extends 
     PagingAndSortingRepository<ExpenseReportAudit, Integer> {

because I failed to add the @Entity annotation to ExpenseReportAudit

@Entity // <--- Adding this fixed the issue.
public class ExpenseReportAudit {
  .....
Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
1
@SpringBootApplication
@MapperScan("com.developer.project.mapper")

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
1

I had a case where i need to inject RestTemplate into a service class. However, the RestTemplate cannot be picked up by the service class. What I did is to create a wrapper class under the same package as main application and mark the wrapper as Component and autowire this component in the service class. Problem solved. hope it also works for you

  • This was my case and the proposed solution worked for me. But I didn't understand why Spring cannot find org.springframework.web.client.RestTemplate. – Cagin Uludamar Dec 07 '22 at 06:09
1

If your class dependency is managing by Spring then this issue may occur if we forgot to add default/empty arg constructor inside our POJO class.

Arif Khan
  • 226
  • 1
  • 2
  • 12
1

There is a chance that you are trying to @autowired an interface before implement the interface.

example solution:

    **HomeController.java**
    class HomeController{

      @Autowired
      UserService userService;
    .....
    }
----------------------------------------------------------------------
    **UserService.java** 
    public interface UserService {
        User findByUsername(String username);
    .....
    }
-----------------------------------------------------------------------
     **UserServiceImpl.java**
     @Service
     public class UserServiceImpl implements UserService{

         public User findByUsername(String username) {
           return userDao.findByUsername(username);
         }
        ....
      }

<i>This is not italic</i>, and [this is not a link](https://example.com)
biddut
  • 353
  • 3
  • 6
  • Please check if you have missed to add Service annotation in your interface implementation class. @Service public class FsProxyImpl implements FSStatusProxy { Override public void getFlightInfoWithConnectingGate(List flightDetailsList) { System.out.println("list val"+flightDetailsList.get(0).getArrivalStation()); } } – Ashu Singh Apr 16 '21 at 06:54
1

@Service should be imported from org.springframework.stereotype.Service

you might be importing it from org.jvnet.hk2.annotations.Service

In CrudRepository, check if the Entity class @Id using import javax.persistence.Id;, not import org.springframework.data.annotation.Id;

yu yang Jian
  • 6,680
  • 7
  • 55
  • 80
1

In my case, our project has a Configuration class, so I just added mine like this

@Configuration
public class DependencyConfiguration {

    @Bean
    public ActivityService activityService(
            @Value("${send.money.ms.activity.url}") final String activityHistoryUrl,
            final HttpRestService httpRestService
    ) {
        return new ActivityServiceImpl(activityHistoryUrl, httpRestService);
    }

.......................

Then the microservice started alright.

PS: I encountered this issue even though the library I need is imported properly and could be seen on External Libraries imported.

iamjoshua
  • 1,157
  • 3
  • 16
  • 33
1

Had the same error, transpired it was an issue with the application properties with incorrect username, password and driver and completely unrelated to Bean.

burgic
  • 11
  • 1
  • 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](/help/how-to-answer). – Community Jun 07 '22 at 10:31
1

I also received a similar error:

Consider defining a bean of type 'A_REPOSITORY_INTERFACE' in your configuration.

Then, according to Akashe's solution, I added @EnableJpaRepositories to my main class. After that, I received the following error instead:

Consider defining a bean of type 'entityManagerFactory' in your configuration.

Next, I went through all the responses here, googled a lot and read a lot of other resources, which didn't worked out.

Finally, I was lucky to have found the solution on a blog/website (javatute.com). I just followed its examples.

Like suggested by many here, I added @ComponentScan("YOUR_BASE_PACKAGE.*") and @EntityScan("YOUR_BASE_PACKAGE.*") to my main app class, followed by adding a config package and creating a JpaConfig class like:

package YOUR_BASE_PACKAGE.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "YOUR_BASE_PACKAGE")
public class JpaConfig {

}

The blog I followed:

Consider defining a bean of type in your configuration

which lead me to:

Error creating bean with name entityManagerFactory defined in class path resource : Invocation of init method failed

and finally to:

Many To Many Mapping In Hibernate/JPA Using Spring Boot And Oracle

Sina
  • 223
  • 1
  • 3
  • 9
0

I think, you are missing the @Bean annotation in your RequestController

Add the Bean in your file, this solved my issue
I got this solution while I was learning Spring Boot from tutorialspoint

private Applicant applicant;

@Bean 
public Applicant applicant() { 
    return new Applicant(); 
}
Vishal Petkar
  • 369
  • 1
  • 4
  • 20
0

Adding Spring Boot Data JPA Starter dependency solved the issue for me.

Maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

Gradle

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.6.RELEASE'

Or you can go directly here

  • This actually doesn't apply in this case. It prompts for connection details to database (Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. ). In a situation where I want to test manually without interacting with the database, this won't work. – Thomas Okonkwo May 12 '20 at 04:04
0

If you use interface you can extends CrudRepository<Applicant,Long> with @Repository annotation.

zawhtut
  • 8,335
  • 5
  • 52
  • 76
0

Issue can also appeared when you use per example @EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE) and later you renamed the package name or moved it in another place.

Very often faced it within a multi-module maven project and spring boot

redoff
  • 1,124
  • 11
  • 18
0

Remove annotation type configuration like @Service from the thread run method.

@Service, @Component
Sandun Susantha
  • 1,010
  • 1
  • 10
  • 11
0

reminder that spring doesn't scan the world , it uses targeted scanning wich means everything under the package where springbootapplication is stored. therefore this error "Consider defining a bean of type 'package' in your configuration [Spring-Boot]" may appear because you have services interfaces in a different springbootapplication package .

0

check the base package name.If the package has different modules that are not prefixed with base package name.

Ajay Takur
  • 6,079
  • 5
  • 39
  • 55
0

To fix errors like:

It happened to me that the LocalContainerEntityManagerFactoryBean class did not have the setPackagesToScan method. Then I proceeded to use the @EntityScan annotation which doesn't work correctly.

Later I could find the method setPackagesToScan() but in another module, so the problem came from the dependency which did not have this method because it was an old version.

This method can be found in the spring-data-jpa or spring-orm dependency of updated versions:

From:

implementation("org.springframework", "spring-orm", "2.5.1") 

To:

implementation("org.springframework", "spring-orm", "5.2.9.RELEASE")

Or to:

implementation("org.springframework.data", "spring-data-jpa", "2.3.4.RELEASE")

In addition, it was not necessary to add other annotations other than that of @SprintBootApplication.

@SpringBootApplication
open class MoebiusApplication : SpringBootServletInitializer()

@Bean
open fun entityManagerFactory() : LocalContainerEntityManagerFactoryBean {
    val em = LocalContainerEntityManagerFactoryBean()
    em.dataSource = dataSource()
    em.setPackagesToScan("app.mobius.domain.entity")
    ... 
}

GL

Source

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
0

For me worked a clean install on pom.xml

  1. right click on pom.xml

  2. expand Run As

  3. select Maven build

  4. set Goals to the command clean install

  5. apply > run > close

MagoVins
  • 9
  • 4
0

If you are using Eclipse and tried all possibilities and you still have errors, then try to update the project using Maven. You can to this like this: Right click on your project-> Maven -> Update Project.

It helped me to solve my errors. Sometimes Eclipse shows this error if a project is not updated with all repos which you declared in the pom file.

JW Geertsma
  • 857
  • 3
  • 13
  • 19
0

I had the same issue while using MongoDB due to incorrect basePackages name of the @Repository class

@Configuration
@EnableMongoRepositories(basePackages = {"org.mycompany.repository.mongo.primary"}, mongoTemplateRef = "getMongoTemplatePrimary")
Prashant S
  • 349
  • 4
  • 14
0

I had a similar issue, exact same error message. But my error only happened when I tried to install and run on my local docker.

Turns out the issue was profile dependant.

I had two classes that implemented the interface, one with a production Profile @Profile("prod") and the second with the "Test Environment" profiles. @Profile("!local & !prod")

However, there was no active profile for when I tried to run locally (on Docker).

I created a 3rd class that implemented the interface for a local profile @Profile("local") and this fixed my issue

R_Shaad
  • 21
  • 3
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30317663) – Bakar Nov 12 '21 at 11:05
0

In my case, I have just added @Component annotations to some classes (to make sure every Classes have configuration).

@Component, @Service or @Repository are almost familiar. Baeldung link reference

YtachY
  • 1
  • 1
0

In my case, this problem was caused by an errant spring.autoconfigure.exclude property value. I had this property because my Spring Boot project initially didn't connect to a database, but then I added my first JpaRepository class and tried to declare an instance of it with the @Autowired annotation in a @RestController class.

The line in application.properties that caused the problem:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

Once I deleted or commented out that line, my Spring Boot service ran just fine.

Gary Sheppard
  • 4,764
  • 3
  • 25
  • 35
0

For me, it was because of using @Value in class that use lombok @RequiredArgsConstructor annotation. Just changed it to constructor injection.

Tohid Makari
  • 1,700
  • 3
  • 15
  • 29
0

I had the same problem, i was get this error for redis repository like this:

@Repository
public interface AppTokenRepository extends CrudRepository<AppToken, String> {
}


@RedisHash("APP_TOKEN")
public class AppToken implements Serializable {
    private String id;
    private String accessToken;
}

I solved my issue by adding @EnableRedisRepositories over spring boot application class.

Rasool Ghafari
  • 4,128
  • 7
  • 44
  • 71
0

I fix it by add this config to Application.java file.

enter image description here

cng.buff
  • 405
  • 4
  • 5
0

This can also happen if you have two beans with the same name.

For example if you have factory method monkey creating Monkey and you mistakenly name another factory method (creating Car) also monkey.

Problematic code:

    @Bean
    public Car monkey() {
        return new Car();
    }

Should be:

    @Bean
    public Car car() {
        return new Car();
    }

Reference:

By default, the bean name will be the same as the method name...

Spring doc 1

Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master and uses it to set the property.

Spring doc 2

Trayan Momkov
  • 842
  • 1
  • 7
  • 18
0

Use @Component for the Class where the Bean is not found. And Use

@ComponentScan("<Use_The_Root_Directory_Of_Main_Class>")

. This can happen when the Components are spread over many directories.

@Configuration
@SpringBootApplication
@ComponentScan({"com.example.demo"})
public class Application {
}
0

i had the "Action: Consider defining a bean of type 'blabla.blabla.blabla.repository' in your configuration." error and this is how i fixed it;

I was work with a MongoDB. that so, my "EmployeeRepo.java interface" had to contains as like this;

**public interface EmployeeRepo extends MongoRepository<Employee, Long> **

Firstly, the area with the MongoRepository part was like this "JPARepository". Then i changed with the MongoRepository. And the problem fixed

0

Try to remove

@ComponentScan({"com.delivery.service","com.delivery.request"})

File WebServiceApplication.java at folder where the most outter of all files/packages.

@SpringBootApplication
public class WebServiceApplication extends SpringBootServletInitializer {

    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(WebServiceApplication.class);
    }

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

}
Vy Do
  • 46,709
  • 59
  • 215
  • 313
-1

For me - using Spring Boot with MongoDB, the following was the Problem:

In my POM.xml I had:

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

but I needed the following:

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

(Short: Add "spring-boot-..." instead of only "spring-...")

ZoellnD
  • 11
  • 4
-1
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
@EnableHystrix
@EnableHystrixDashboard
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

  • Welcome to SO. Try to add something more than a code snippet to your answers, to explain what it is you want to contribute to the topic. – H3AR7B3A7 Jul 06 '22 at 22:44