Consider defining a bean of type 'package' in your configuration [Spring-Boot]

JavaSpring Boot

Java Problem Overview


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 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.

Java Solutions


Solution 1 - Java

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 {

Solution 2 - Java

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

Solution 3 - Java

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."

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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).

Solution 10 - Java

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

Solution 11 - Java

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.

Solution 12 - Java

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:

Solution 13 - Java

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

Solution 14 - Java

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.

Solution 15 - Java

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

Solution 16 - Java

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;

Solution 17 - Java

@Configuration annotation will just solve the error

Solution 18 - Java

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.

Solution 19 - Java

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.

Solution 20 - Java

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> {

Solution 21 - Java

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 {
  .....

Solution 22 - Java

@SpringBootApplication
@MapperScan("com.developer.project.mapper")

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

Solution 23 - Java

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.

Solution 24 - Java

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>

Solution 25 - Java

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

Solution 26 - Java

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.

Solution 27 - Java

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

Solution 28 - Java

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(); 
}

Solution 29 - Java

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

Solution 30 - Java

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

Solution 31 - Java

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

Solution 32 - Java

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)

Solution 33 - Java

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

@Service, @Component

Solution 34 - Java

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 .

Solution 35 - Java

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

Solution 36 - Java

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

Solution 37 - Java

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

Solution 38 - Java

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.

Solution 39 - Java

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

Solution 40 - Java

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

Solution 41 - Java

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

Solution 42 - Java

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.

Solution 43 - Java

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

Solution 44 - Java

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

Solution 45 - Java

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike3355View Question on Stackoverflow
Solution 1 - JavaMike3355View Answer on Stackoverflow
Solution 2 - JavaCodeWorldView Answer on Stackoverflow
Solution 3 - JavaameenhereView Answer on Stackoverflow
Solution 4 - JavaCarlos MarcanoView Answer on Stackoverflow
Solution 5 - JavaMohammad FalahiView Answer on Stackoverflow
Solution 6 - JavaASHWANI PANDEYView Answer on Stackoverflow
Solution 7 - JavaDawid GorczycaView Answer on Stackoverflow
Solution 8 - Javaalexis_diaView Answer on Stackoverflow
Solution 9 - JavaeriegzView Answer on Stackoverflow
Solution 10 - JavaTushar Saha ChowdhuryView Answer on Stackoverflow
Solution 11 - JavaSriharsha g.r.vView Answer on Stackoverflow
Solution 12 - JavaLove KumarView Answer on Stackoverflow
Solution 13 - JavaChakriView Answer on Stackoverflow
Solution 14 - JavaHearenView Answer on Stackoverflow
Solution 15 - JavaArielView Answer on Stackoverflow
Solution 16 - JavaWashington da SilvaView Answer on Stackoverflow
Solution 17 - Javaoludamilare olukotunView Answer on Stackoverflow
Solution 18 - JavaRoss MillsView Answer on Stackoverflow
Solution 19 - Javauser13650952View Answer on Stackoverflow
Solution 20 - JavaBarani rView Answer on Stackoverflow
Solution 21 - JavaOjonugwa Jude OchalifuView Answer on Stackoverflow
Solution 22 - Javadeveloper07View Answer on Stackoverflow
Solution 23 - JavaArif KhanView Answer on Stackoverflow
Solution 24 - Javauser1441323View Answer on Stackoverflow
Solution 25 - JavaStaxxView Answer on Stackoverflow
Solution 26 - JavaiamjoshuaView Answer on Stackoverflow
Solution 27 - Javauser11976602View Answer on Stackoverflow
Solution 28 - JavaVishal PetkarView Answer on Stackoverflow
Solution 29 - JavaJohny Thomas KariathView Answer on Stackoverflow
Solution 30 - JavazawhtutView Answer on Stackoverflow
Solution 31 - JavaredoffView Answer on Stackoverflow
Solution 32 - JavabiddutView Answer on Stackoverflow
Solution 33 - JavaSandun SusanthaView Answer on Stackoverflow
Solution 34 - JavapopcornwView Answer on Stackoverflow
Solution 35 - JavaAjay TakurView Answer on Stackoverflow
Solution 36 - JavaBraian CoronelView Answer on Stackoverflow
Solution 37 - JavaMagoVinsView Answer on Stackoverflow
Solution 38 - JavaPrathamesh SangaView Answer on Stackoverflow
Solution 39 - JavaPrashant SView Answer on Stackoverflow
Solution 40 - JavaR_ShaadView Answer on Stackoverflow
Solution 41 - JavaYtachYView Answer on Stackoverflow
Solution 42 - JavaGary SheppardView Answer on Stackoverflow
Solution 43 - JavaTohid MakariView Answer on Stackoverflow
Solution 44 - JavaZoellnDView Answer on Stackoverflow
Solution 45 - JavaJoão Pedro Andrade MarquesView Answer on Stackoverflow