Error creating bean with name controller

i've been trying do some application with spring-boot and hibernate the last few days, i could correct all the errors, but this one i can't understand... i have created 3 packages : Model which co...

If you follow the stack trace, and read it carefully, you can figure this out.

The first exception:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘notebookRestController’: Unsatisfied dependency expressed through field ‘notebookRepository’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘notebookRepository’: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.notedemo.repository.NotebookRepository.findAllByUser_UId(long)!

OK, so it failed creating notebookRestController because there was a problem creating notebookRepsitory. Let’s continue:

Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.notedemo.repository.NotebookRepository.findAllByUser_UId(long)!

Ah, so the problem is with the query! It failed parsing the query, so it failed to create NotebookRepository, and since it required that repository to create NotebookRestController, it failed to create that as well. Makes perfect sense.

So, the problem is with the query

select e from Notebook e where Notebook.user.uId=:x

I think the problem is you are using Notebook instead of e. I would try

select e from Notebook e where e.user.uId=:x

1. Overview

In this tutorial, we’ll discuss the Spring org.springframework.beans.factory.BeanCreationException. It’s a very common exception thrown when the BeanFactory creates beans of the bean definitions, and encounteres a problem. This article will explore the most common causes of this exception, along with the solutions.

2. Cause: org.springframework.beans.factory.NoSuchBeanDefinitionException

By far, the most common cause of the BeanCreationException is Spring trying to inject a bean that doesn’t exist in the context.

For example, BeanA is trying to inject BeanB:

@Component
public class BeanA {

    @Autowired
    private BeanB dependency;
    ...
}

If a BeanB isn’t found in the context, then the following exception will be thrown (Error Creating Bean):

Error creating bean with name 'beanA': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private com.baeldung.web.BeanB cpm.baeldung.web.BeanA.dependency; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [com.baeldung.web.BeanB] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

To diagnose this type of issue, we’ll first make sure the bean is declared:

  • either in an XML configuration file using the <bean /> element
  • or in a Java @Configuration class via the @Bean annotation
  • or is annotated with @Component, @Repository, @Service, @Controller, and classpath scanning is active for that package

We’ll also check that Spring actually picks up the configuration files or classes, and loads them into the main context.

3. Cause: org.springframework.beans.factory.NoUniqueBeanDefinitionException

Another similar cause for the bean creation exception is Spring trying to inject a bean by type, namely by its interface, and finding two or more beans implementing that interface in the context.

For example, BeanB1 and BeanB2 both implement the same interface:

@Component
public class BeanB1 implements IBeanB { ... }
@Component
public class BeanB2 implements IBeanB { ... }

@Component
public class BeanA {

    @Autowired
    private IBeanB dependency;
    ...
}

This will lead to the following exception being thrown by the Spring bean factory:

Error creating bean with name 'beanA': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private com.baeldung.web.IBeanB com.baeldung.web.BeanA.b; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type [com.baeldung.web.IBeanB] is defined: 
expected single matching bean but found 2: beanB1,beanB2

4. Cause: org.springframework.beans.BeanInstantiationException

4.1. Custom Exception

Next in line is a bean that throws an exception during its creation process. A simplified example to easily understand the problem is throwing an exception in the constructor of the bean:

@Component
public class BeanA {

    public BeanA() {
        super();
        throw new NullPointerException();
    }
    ...
}

As expected, this will lead to Spring failing fast with the following exception:

Error creating bean with name 'beanA' defined in file [...BeanA.class]: 
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [com.baeldung.web.BeanA]: 
Constructor threw exception; 
nested exception is java.lang.NullPointerException

4.2. java.lang.InstantiationException

Another possible occurence of the BeanInstantiationException is defining an abstract class as a bean in XML; this has to be in XML because there’s no way to do it in a Java @Configuration file, and classpath scanning will ignore the abstract class:

@Component
public abstract class BeanA implements IBeanA { ... }

Here’s the XML definition of the bean:

<bean id="beanA" class="com.baeldung.web.BeanA" />

This setup will result in a similar exception:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'beanA' defined in class path resource [beansInXml.xml]: 
Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [com.baeldung.web.BeanA]: 
Is it an abstract class?; 
nested exception is java.lang.InstantiationException

4.3. java.lang.NoSuchMethodException

If a bean has no default constructor, and Spring tries to instantiate it by looking for that constructor, this will result in a runtime exception:

@Component
public class BeanA implements IBeanA {

    public BeanA(final String name) {
        super();
        System.out.println(name);
    }
}

When the classpath scanning mechanism picks up this bean, the failure will be:

Error creating bean with name 'beanA' defined in file [...BeanA.class]: Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [com.baeldung.web.BeanA]: 
No default constructor found; 
nested exception is java.lang.NoSuchMethodException: com.baeldung.web.BeanA.<init>()

A similar exception, but harder to diagnose, may occur when the Spring dependencies on the classpath don’t have the same version. This kind of version incompatibility may result in a NoSuchMethodException because of API changes. The solution to such a problem is to make sure all Spring libraries have the exact same version in the project.

5. Cause: org.springframework.beans.NotWritablePropertyException

Yet another possiblity is defining a bean, BeanA, with a reference to another bean, BeanB, without having the corresponding setter method in BeanA:

@Component
public class BeanA {
    private IBeanB dependency;
    ...
}
@Component
public class BeanB implements IBeanB { ... }

Here’s  the Spring XML Configuration:

<bean id="beanA" class="com.baeldung.web.BeanA">
    <property name="beanB" ref="beanB" />
</bean>

Again, this can only occur in XML Configuration because when using Java @Configuration, the compiler will make this issue impossible to reproduce.

Of course, in order to solve this issue, we need to add the setter for IBeanB:

@Component
public class BeanA {
    private IBeanB dependency;

    public void setDependency(final IBeanB dependency) {
        this.dependency = dependency;
    }
}

6. Cause: org.springframework.beans.factory.CannotLoadBeanClassException

Spring throws this exception when it can’t load the class of the defined bean. This may occur if the Spring XML Configuration contains a bean that simply doesn’t have a corresponding class. For example, if class BeanZ doesn’t exist, the following definition will result in an exception:

<bean id="beanZ" class="com.baeldung.web.BeanZ" />

The root cause of the ClassNotFoundException and the full exception in this case is:

nested exception is org.springframework.beans.factory.BeanCreationException: 
...
nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: 
Cannot find class [com.baeldung.web.BeanZ] for bean with name 'beanZ' 
defined in class path resource [beansInXml.xml]; 
nested exception is java.lang.ClassNotFoundException: com.baeldung.web.BeanZ

7. Children of BeanCreationException

7.1. The org.springframework.beans.factory.BeanCurrentlyInCreationException

One of the subclasses of BeanCreationException is the BeanCurrentlyInCreationException. This usually occurs when using constructor injection, for example, in a case of circular dependencies:

@Component
public class BeanA implements IBeanA {
    private IBeanB beanB;

    @Autowired
    public BeanA(final IBeanB beanB) {
        super();
        this.beanB = beanB;
    }
}
@Component
public class BeanB implements IBeanB {
    final IBeanA beanA;

    @Autowired
    public BeanB(final IBeanA beanA) {
        super();
        this.beanA = beanA;
    }
}

Spring won’t be able to resolve this kind of wiring scenario and the end result will be:

org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: Is there an unresolvable circular reference?

The full exception is very verbose:

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'beanA' defined in file [...BeanA.class]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [com.baeldung.web.IBeanB]: : 
Error creating bean with name 'beanB' defined in file [...BeanB.class]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [com.baeldung.web.IBeanA]: : 
Error creating bean with name 'beanA': Requested bean is currently in creation: 
Is there an unresolvable circular reference?; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: 
Is there an unresolvable circular reference?; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'beanB' defined in file [...BeanB.class]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [com.baeldung.web.IBeanA]: : 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: 
Is there an unresolvable circular reference?; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: Is there an unresolvable circular reference?

7.2. The org.springframework.beans.factory.BeanIsAbstractException

This instantiation exception may occur when the Bean Factory attempts to retrieve and instantiate a bean that was declared as abstract:

public abstract class BeanA implements IBeanA {
   ...
}

We declare it in the XML Configuration as:

<bean id="beanA" abstract="true" class="com.baeldung.web.BeanA" />

If we try to retrieve BeanA from the Spring Context by name, like when instantiating another bean:

@Configuration
public class Config {
    @Autowired
    BeanFactory beanFactory;

    @Bean
    public BeanB beanB() {
        beanFactory.getBean("beanA");
        return new BeanB();
    }
}

This will result in the following exception:

org.springframework.beans.factory.BeanIsAbstractException: 
Error creating bean with name 'beanA': Bean definition is abstract

And the full exception stacktrace:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'beanB' defined in class path resource 
[org/baeldung/spring/config/WebConfig.class]: Instantiation of bean failed; 
nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: 
Factory method 
[public com.baeldung.web.BeanB com.baeldung.spring.config.WebConfig.beanB()] threw exception; 
nested exception is org.springframework.beans.factory.BeanIsAbstractException: 
Error creating bean with name 'beanA': Bean definition is abstract

8. Conclusion

In this article, we learned how to navigate the variety of causes and problems that may lead to a BeanCreationException in Spring, as well as developed a good grasp on how to fix all of these problems.

The implementation of all the exception examples can be found in the github project. This is an Eclipse based project, so it should be easy to import and run as it is.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> THE COURSE

Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

The Spring framework is one of the most popular frameworks for developing Java applications. Apart from many goodies, it also provides a DI and IOC container that initializes objects and their dependencies and assembles them together. The Java classes created and maintained by Spring are called Spring bean. At the startup, when the Spring framework initializes the system by creating objects and their dependencies depending upon @Autowired annotation or spring configuration XML file, it throws «org.springframework.beans.factory.BeanCreationException: Error creating a bean with name X» error if it is not able to instantiate a particular Spring bean.

There could be numerous reasons why Spring could not able to create a bean with name X, but clue always lies on the detailed stack trace. This error always has some underlying cause e.g. a ClassNotFoundException or a NoClassDefFoundError, which potentially signal a missing JAR file in the classpath.

In short, you should always give a detailed look at the stack trace of your error message and find out the exact cause of «org.springframework.beans.factory.BeanCreationException: Error creating a bean with name» error. The solution would vary accordingly. Btw,  If you are curious about how dependency injection works in Spring and how Spring initializes and wires dependencies together, you should read the first few recipes of Spring Recipes book, where you will find a good explanation of IOC and DI containers.

In this article, I’ll share two of the most common reasons for «org.springframework.beans.factory.BeanCreationException: Error creating a bean with name» error in Spring-based Java application and their solutions. These are just based on my limited experience with using Spring framework in core Java application and Java web application if you have come across any other reasons for BeanCreationException in Spring, don’t forget to share with us in comments.

By the way, if you are new to the Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at these best Spring Framework courses, one of the comprehensive and hands-on resource to learn modern Spring. It’ also the most up-to-date and covers Spring 5. It’s also very affordable and you can buy in just $10 on Udemy sales which happen every now and then.

1) No default constructor on Spring Bean

One of the common mistakes Java programmers make is they forget to define a no-argument constructor in their Spring Bean. If you remember, a spring bean is nothing but a Java class instantiated and managed by Spring. If you also remember, Java compiler adds a default no-argument constructor if you don’t define any, but if you do then it will not insert. It becomes the developer’s responsibility.

Many Java programmer defines a constructor which accepts one or two-argument and forget about the default no-argument constructor, which result in org.springframework.beans.factory.BeanCreationException: Error creating bean with the name at runtime as shown below:

ERROR: org.springframework.web.servlet.DispatcherServlet — Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘InterestRateController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.abc.project.model.service.InterestRateServiceImpl com.abc.project.controller.InterestRateController.InterestRateServ; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘InterestRateServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.abc.project.model.service.InterestRateServiceImpl.setInterestRateDAO(com.abc.project.model.dao.InterestRateDAO); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘InterestRateDAO’ defined in file [C:Userszouhairworkspace.metadata.pluginsorg.eclipse.wst.server.coretmp1wtpwebappsTESTERWEB-INFclassescomabcprojectmodeldaoInterestRateDAO.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.abc.project.model.dao.InterestRateDAO]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.abc.project.model.dao.InterestRateDAO.()
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)

The most important line in this stack trace is

«No default constructor found; nested exception is java.lang.NoSuchMethodException: com.abc.project.model.dao.InterestRateDAO.()»

which is often overlooked by Java programmers.

2) Spring Bean dependent on third party library

If your Spring bean is using a third party library and that library is not available in the classpath at runtime, Spring will again throw
«org.springframework.beans.factory.BeanCreationException: Error creating a bean with name» error. When you look at the stack trace just look for the «Caused By» keyword, this often gives clues about the real error which is causing the problem. Sometimes this can be a ClassNotFoundException while other times a NoClassDefFoundError.

Here is a code snippet which defines beans in Spring configuration and how one single bean is used as a dependency for several other beans. The bean is created and maintained by the Spring IOC container.

That’s all about how to resolve org.springframework.beans.factory.BeanCreationException: Error creating a bean with the name in Java. As I said, most of the time the clue of the root cause lies in the nested exception. You should always pay attention to the «Caused By» keyword. As I said before, this list is by no means complete and these are just a couple of reasons from numerous others which cause this problem. If you come across any other reasons in your project then please share with us.

Other Java Spring articles you may like to explore

  • Spring HelloWorld example using Dependency Injection (tutorial)
  • Difference between Setter and Constructor Injection in Spring? (answer)
  • Difference between BeanFactory and ApplicationContext in Spring? (answer)
  • How to call stored procedures using the Spring framework in Java? (example)
  • What is the bean scope in the Spring framework? (answer)
  • How to implement LDAP authentication using Spring Security? (example)
  • How to implement RBAC (Role-based access control) using Spring? (tutorial)
  • How to limit the number of user sessions using Spring Security? (solution)
  • 5 Books to Learn Spring Framework (books)
  • How to use JDBC database connection pooling with Spring? (tutorial)

P.S. — If you want to learn how to develop RESTful Web Service using Spring MVC in-depth, I suggest you join these free Spring Framework courses. One of the best courses to learn REST with Spring MVC. 

Hi,

I am trying to integrate spring with swagger. got this error. any help is highly appreciated. thank you.

Error while starting the LUIS server

[WARN ] org.springframework.web.context.support.XmlWebApplicationContext: Exception encountered during context initialization — cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘swagger2Controller’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String springfox.documentation.swagger2.web.Swagger2Controller.hostNameOverride; nested exception is java.lang.IllegalArgumentException: Cannot convert value [com.lloydstsb.luis.jndi.JNDIContext@3a47fe {}] from source type [JNDIContext] to target type [String]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:740)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:238)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1238)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:683)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:480)
at org.mortbay.jetty.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:250)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:172)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.Server.doStart(Server.java:275)
at org.mortbay.jetty.plugin.JettyServer.doStart(JettyServer.java:65)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:404)
at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:282)
at org.mortbay.jetty.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
at com.lloydstsb.luis.mojo.LUISRunMojo.execute(LUISRunMojo.java:222)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String springfox.documentation.swagger2.web.Swagger2Controller.hostNameOverride; nested exception is java.lang.IllegalArgumentException: Cannot convert value [com.lloydstsb.luis.jndi.JNDIContext@3a47fe {}] from source type [JNDIContext] to target type [String]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
… 55 more
Caused by: java.lang.IllegalArgumentException: Cannot convert value [com.lloydstsb.luis.jndi.JNDIContext@3a47fe {}] from source type [JNDIContext] to target type [String]
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:94)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:60)
at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:511)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:135)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:132)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84)
at org.springframework.core.env.PropertySourcesPropertyResolver.getPropertyAsRawString(PropertySourcesPropertyResolver.java:70)
at org.springframework.core.env.AbstractPropertyResolver$1.resolvePlaceholder(AbstractPropertyResolver.java:207)
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:147)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
at org.springframework.core.env.AbstractPropertyResolver.resolvePlaceholders(AbstractPropertyResolver.java:170)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:174)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:801)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:955)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
… 57 more
[ERROR] org.springframework.web.context.ContextLoader: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘swagger2Controller’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String springfox.documentation.swagger2.web.Swagger2Controller.hostNameOverride; nested exception is java.lang.IllegalArgumentException: Cannot convert value [com.lloydstsb.luis.jndi.JNDIContext@3a47fe {}] from source type [JNDIContext] to target type [String]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:740)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:238)

// SwaggerConfig.java 
@Configuration
@EnableSwagger2
@Component
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }
}

// HelloController.java
@RestController
public class HelloController {

    @GET
    @Path("/hello/{name}")
    @Produces({APPLICATION_JSON})
    public String hello(@PathParam("name") String name) {
        String result = "Hello " + name + ". How are you?";
        return result;
    }
}

Maven.xml

<spring.version>4.1.7.RELEASE</spring.version>
<com.fasterxml.jackson.version>2.7.3</com.fasterxml.jackson.version>

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aop</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aspects</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-beans</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-expression</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-instrument</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-orm</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-oxm</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-tx</artifactId>
	<version>${spring.version}</version>
</dependency>

<!-- Jackson JSON dependencies -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.module</groupId>
	<artifactId>jackson-module-jaxb-annotations</artifactId>
	<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.datatype</groupId>
	<artifactId>jackson-datatype-joda</artifactId>
	<version>${com.fasterxml.jackson.version}</version>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>servlet-api</artifactId>
	<version>2.5</version>
	<scope>provided</scope>
</dependency>
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.12</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.3.0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.3.0</version>
</dependency>

ApplicationContext.xml
<bean class="com.swaggerTest.HelloController" />
<bean class="com.swaggerTest.SwaggerConfig" />
<bean class="springfox.documentation.spring.web.plugins.Docket" />


Web.xml
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="com.swaggerTest" />
    <context:annotation-config/>
    <bean class="com.SwaggerConfig"/>

    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
    <mvc:resources mapping="/webjars/**"
                   location="classpath:/META-INF/resources/webjars/" />
</beans>

Last Updated:  August 27, 2021 | Published: December 2, 2020

When working for the first time with Spring, you might encounter several no qualifying bean exceptions when you try to start your application. The stack trace is quite long for such error scenarios and it might become frustrating as your application doesn’t start. The same is true whenever your test works with a Spring Test Context. Most of the time, the root cause for this is easy to fix. With this article, I’m covering a set of common pitfalls of why Spring is unable to resolve a bean when writing tests for a Spring Boot application.

The following examples are using JUnit 5 together with Spring Boot > 2.2.0.RELEASE

The Spring Bean is not part of the sliced Spring Context

A common scenario is the following: We have a Spring MVC controller endpoint that has several collaborators. During runtime, Spring injects these collaborators and the endpoint can do its work.

Let’s take the PublicController as a simplified example for this common use case:

@RestController

@RequestMapping(«/public»)

public class PublicController {

  private final UserService userService;

  public PublicController(UserService userService) {

    this.userService = userService;

  }

  // … endpoint definitions

}

When testing this controller, we can use @WebMvcTest to test the controller with MockMvc. In addition to this, we get a sliced Spring Context that contains only relevant Spring Beans for this test.

If we would now write the following test setup and try to inject both an instance of MockMvc and the UserService

@WebMvcTest(PublicController.class)

class PublicControllerTest {

  @Autowired

  private MockMvc mockMvc;

  @Autowired

  private UserService userService;

  // … tests

}

… any test inside this test class will fail with the following (reduced) stack trace:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:

    Error creating bean with name ‘publicController’ defined in file [/home/rieckpil/development/git/sample-project/target/classes/de/rieckpil/blog/PublicController.class]:

    Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:

    No qualifying bean of type ‘de.rieckpil.learning.UserService’ available:

    expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

    … 68 more

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:

    No qualifying bean of type ‘de.rieckpil.learning.UserService’ available:

    expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

    … 87 more

These stack traces can be very long and might be overwhelming especially if you are new to Spring and Spring Boot. What’s important here is the NoSuchBeanDefinitionException which causes the UnsatisfiedDependencyException. During context initialization, Spring is trying to instantiate the PublicController.  As this controller has one collaborator (UserService), Spring tries to resolve this dependency by injecting it from its context.

But there is no available bean of type UserService inside the test context as we are using @WebMvcTest which only populates MVC components. This ignores populating any non-relevant @Service or @Component classes.

In the end, this whole chain results in an IllegalStateException as Spring is not able to load the ApplicationContext. This will fail our test before we can even execute any test logic.

When testing different slices of our application in isolation, we can fix this unresolved bean exception by providing a mocked bean.

@WebMvcTest(PublicController.class)

class PublicControllerTest {

  @Autowired

  private MockMvc mockMvc;

  @MockBean

  private UserService userService;

  // …

}

This will place a bean of the UserService inside the Spring Test Context. However, this bean doesn’t represent the actual completion and is a mocked version of it. Please note that this @MockBean is different from Mockito’s @Mock.

We can also add a real bean to our context, which we’ll see in the last section of this article.

No qualifying bean because of untriggered auto-configuration

Another common error scenario is that we expect a specific auto-configuration mechanism to trigger, but it doesn’t for our test setup.

A good example is the auto-configuration of the WebTestClient or RestTestTemplate which only happens when we start the embedded Servlet container during a test.

Using @SpringBootTest without any further configuration will use a mocked Servlet environment. That’s why the following test:

@SpringBootTest

class ApplicationIT {

  @Autowired

  private WebTestClient webTestClient;

  @Test

  void shouldReturn200ForPublicEndpoint() {

    // …

  }

}

… fails as the WebTestclient is not resolvable:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘de.rieckpil.blog.ApplicationIT’:

  Unsatisfied dependency expressed through field ‘webTestClient’;

  nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:

  No qualifying bean of type ‘org.springframework.test.web.reactive.server.WebTestClient’ available:

  expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:

  {@org.springframework.beans.factory.annotation.Autowired(required=true)}

The fix for this is simple:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

class ApplicationIT {

  @Autowired

  private WebTestClient webTestClient;

}

If you are using IntelliJ IDEA, you’ll also get hints before runtime if you’ll be able to inject a specific bean for your test. This is quite helpful if we forget e.g. to use @Serivce or @Component on top of our classes.

However, there are also false-positives where IDEA thinks we are unable to autowire a bean during tests. This usually happens for scenarios where we programmatically register beans or for more advanced setups.

Spring Boot also provides several meta-annotations to enable auto-configuration explicitly:

  • @AutoConfigureTestDatabase auto-configures a DataSource using an embedded database by default
  • @AutoConfigureCache to auto-configure a test CacheManager
  • @AutoConfigureMockRestServiceService to auto-configure a MockRestServivceServer to test a RestTemplate usage
  • etc.

We are writing a unit test without a Spring Context

Let’s take a look at the next possible pitfall when testing our application. This time we want to write a unit test to verify the UserService. This class has one collaborator (the EntityManager) and takes care of creating new users:

@Service

public class UserService {

  private final EntityManager entityManager;

  public UserService(EntityManager entityManager) {

    this.entityManager = entityManager;

  }

  public void create(String username) {

    // create the user

  }

}

Now when it comes to testing, developers sometimes mix concepts of plain unit testing and writing tests with support from Spring and Spring Boot. This might end up in the following (wrong) test setup.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// wrong test setup, won’t work

@ExtendWith(MockitoExtension.class)

class UserServiceTest {

  @Autowired

  private EntityManager entityManager;

  private UserService userService;

  @Test

  void shouldCreateUser() {

    this.userService = new UserService(entityManager);

    // possible NullPointerExceptions as the entityManager is null

    this.userService.create(«duke»);

  }

}

As we are writing our application with Spring Boot, one might think that we are able to inject our beans anywhere. This is not the case here. For the test above no Spring Test Context is created at all and the entityManager field is null. We also don’t register the SpringExtension here that takes care of injecting the beans for our test.

The correct way in this example would be to only rely on tools that JUnit 5 and Mockito provide.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import org.junit.jupiter.api.Test;

import org.junit.jupiter.api.extension.ExtendWith;

import org.mockito.InjectMocks;

import org.mockito.Mock;

import org.mockito.junit.jupiter.MockitoExtension;

import javax.persistence.EntityManager;

@ExtendWith(MockitoExtension.class)

class UserServiceTest {

  @Mock

  private EntityManager entityManager;

  @InjectMocks

  private UserService userService;

  @Test

  void shouldCreateUser() {

    // test logic

  }

}

The import section on top of the class is a great indicator to verify that we are not using anything from Spring or Spring Boot for our unit tests.

In this context, it’s also important to understand the difference between @Mock and @MockBean.

The Spring Boot main class defines logic and has collaborators

Sometimes projects define Spring Beans or startup logic inside the Spring Boot main entry point class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@SpringBootApplication

public class Application implements CommandLineRunner {

  private final DataSource dataSource;

  public Application(DataSource dataSource) {

    this.dataSource = dataSource;

  }

  public static void main(String[] args) {

    SpringApplication.run(Application.class, args);

  }

  @Override

  public void run(String... args) throws Exception {

    System.out.println(«Connection to database successful: «

      + dataSource.getConnection().getMetaData().getDatabaseProductName());

  }

}

The logic above will always be triggered whenever we use a Spring Boot test slice annotation like @WebMvcTest or @DataJpaTest. We would see failing web layer tests because Spring is unable to load the ApplicationContext as it can’t resolve the DataSource bean. That’s an overhead we can avoid and we should keep our Spring Boot entry point class as empty as possible.

We can outsource our bean definitions to dedicated @Configuration classes. Otherwise, all your test that load an ApplicationContext would have to satisfy the collaborators of your main class.

The same is true for any startup logic that we might want to define at this point.

Adding any Spring Bean to our Spring Test Context

We now saw how we can fix common pitfalls when Spring is unable to resolve a bean. Up until this point we used @MockBean to place a mocked version of a Spring Bean inside the Spring Test Context. However, there might be scenarios where we don’t want a mocked instance and rather a real one. Let’s see how we can achieve this.

For demonstration purposes, we’ll enrich the PublicController and add an additional collaborator: MeterRegistry.

@RestController

@RequestMapping(«/public»)

public class PublicController {

  private final UserService userService;

  private final MeterRegistry meterRegistry;

  public PublicController(UserService userService, MeterRegistry meterRegistry) {

    this.userService = userService;

    this.meterRegistry = meterRegistry;

  }

  // endpoint definitions

}

Coming back to the same test we already saw before, we now have to decide what to do with both collaborators. By default, they are not part of the Spring Test Context, as @WebMvcTest only populates relevant Spring MVC components (speak Spring Beans).

Mocking the collaborator with @MockBean is always a valid option, but this time we want to add a real MeterRegistry instance to our Spring Test Context.

To achieve this, we can make use of Spring’s @TestConfiguration annotation and create a nested static class that defines beans. For our example, it’s only one as we want to still mock the UserService bean.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

@WebMvcTest(PublicController.class)

class PublicControllerTest {

  @Autowired

  private MockMvc mockMvc;

  @Autowired

  private MeterRegistry meterRegistry;

  @MockBean

  private UserService userService;

  @TestConfiguration

  static class TestConfig {

    @Bean

    public MeterRegistry meterRegistry() {

      return new SimpleMeterRegistry();

    }

  }

}

With this setup, our test is now able to load the Spring Test Context and can inject all collaborators to our PublicController. This solution gives us a lot of control as we can decide for every collaborator to either mock it or provide the actual implementation.

We can even outsource this test configuration to a dedicated class …

@TestConfiguration

public class DefaultRegistryConfig {

  @Bean

  public MeterRegistry meterRegistry() {

    return new SimpleMeterRegistry();

  }

}

… to reuse it for other tests with @Import:

@WebMvcTest(PublicController.class)

@Import(DefaultRegistryConfig.class)

class PublicControllerTest {

  // no nested @TestConfiguration class needed and we can reuse it

}

This approach allows us to add the real Spring Beans to our test context and e.g. test our web layer in combination with its real collaborator. In general, we should still favor mocking any interaction to the outside (speak to a collaborator) whenever we want to test our classes in isolation.

Have fun fixing your unresolved (no qualifying) Spring Bean exceptions,

Philip

spring-logo.jpg

Overview

When developing Java applications using the Spring Framework, our code may compile successfully but application startup will fail if something isn’t configured correctly in Spring.

Two common startup errors are UnsatisfiedDependencyException and NoSuchBeanDefinitionException.

In this article, we’ll explain why these happen and how to fix them.  Since Spring beans can be configured using either Java annotations or XML, we’ll cover both approaches.

Exceptions

Spring attempts to create beans and wire them up during application startup.   

UnsatisfiedDependencyException

Spring is telling us that it could not inject a dependency for one of our classes.

This exception is often triggered by another exception called NoSuchBeanDefinitionException.

NoSuchBeanDefinitionException

Spring is telling us that it couldn’t find a corresponding bean in the application context.   The application context is the container where Spring-managed beans live.

This can happen for a couple reasons:

  • There are no beans defined by that name or type
  • There is more than one bean defined but Spring was unable to determine which one to use

Code Examples

In order to demonstrate these exceptions, we’ll start with working code examples and then break them on purpose.

Spring Boot (annotation-based configuration)

DemoApplication.java

This is a standard main method for a Spring Boot application.   

package com.codebyamir.demo;

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

@SpringBootApplication
public class DemoApplication {

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

The @SpringBootApplication annotation on line 6 enables component scanning which means that classes will be scanned for specific annotations for the purposes of automatic bean creation.

UserService.java

Let’s create an empty service named UserService:

package com.codebyamir.demo;

import org.springframework.stereotype.Service;

@Service
public class UserService {}

The @Service annotation on line 5 informs Spring to register a bean from this class named userService. Bean names are the camelcase version of the class name.

PageController.java

Next, we’ll create an empty controller named PageController annotated with @Controller.   

We then automatically wire our service as a dependency with @Autowired.

package com.codebyamir.demo;

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

@Controller
public class PageController {

  @Autowired
  private UserService userService;

}

Spring Startup

Let’s start the application and check the console log:

2018-04-30 12:57:27.675  INFO 43413 --- [  restartedMain] com.codebyamir.demo.DemoApplication             : Started DemoApplication in 2.262 seconds (JVM running for 2.882)

Everything looks good!

Let’s Break It

Let’s remove the @Service annotation from the UserService class:

package com.codebyamir.demo;

public class UserService {}

Restart the application, and notice that Spring now throws multiple exceptions in the console log:

2018-04-30 12:59:10.986  WARN 41836 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'pageController': Unsatisfied dependency expressed through field 'userService';

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'com.codebyamir.demo.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)

What’s Happening Under the Hood

  • We removed the @Service annotation so Spring doesn’t create a bean from the UserService class.
  •  

  • Spring attempts to autowire the userService field into the controller but fails to find a suitable bean which then causes creation of the controller bean to fail.

Spring (XML-based configuration)

Let’s take a look at another example using the Spring framework with XML-based configuration.

DemoApplication.java

package com.codebyamir.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
      CustomerService cs = context.getBean("customerService", CustomerService.class);
	
      System.out.println(cs.getMessage());
   }
}
  • Line 8 loads the Spring configuration file.    
  • Line 10 retrieves the bean with id=myCustomerService from the Spring container.  
  • Line 12 calls getMessage() on the bean which returns «Hello World».

CustomerService.java

package com.codebyamir.demo;

public interface CustomerService {
	public String getMessage();
}

CustomerServiceImpl.java

package com.codebyamir.demo;

public class CustomerServiceImpl implements CustomerService {
	@Override
	public String getMessage() {
		return "Hello World";
	}
}

applicationContext.xml

Our XML configuration file includes the bean definitions.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <bean id="customerService"
        class="com.codebyamir.demo.CustomerServiceImpl" />
 
</beans>

Spring Startup

Apr 30, 2018 8:59:08 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@53bd815b: startup date [Mon Apr 30 20:59:08 EDT 2018]; root of context hierarchy

Apr 30, 2018 8:59:08 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [applicationContext.xml]

Hello World

Let’s Break It

Let’s comment out the bean definition in the XML file:

<!-- <bean id="customerService"
        class="com.codebyamir.demo.CustomerServiceImpl" />  -->

Now restart the application:

Apr 30, 2018 9:08:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@53bd815b: startup date [Mon Apr 30 21:08:20 EDT 2018]; root of context hierarchy

Apr 30, 2018 9:08:20 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [applicationContext.xml]

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' available

at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:685)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1205)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)

at com.codebyamir.demo.DemoApplication.main(DemoApplication.java:10)

The spring boot exception org.springframework.beans.factory.BeanCreationException: Error creating bean with name happens when a problem occurs when the BeanFactory creates a bean. If the BeanFactory encounters an error when creating a bean from either bean definition or auto-configuration, the BeanCreationException will be thrown. The exception Error creating bean with name defined in file happens most of the time in the @Autowired annotation.

If BeanCreationException is found in the spring boot application, the nested exception would reveal the root cause of the exception. There are multiple nested exceptions that trigger BeanCreationException: Error creating bean with name in the spring boot application.

The nested exception will help you to fix BeanCreationException. The following list describes the common root causes that are seen in the nested exception.

NoSuchBeanDefinitionException: No qualifying bean of type

This exception occurs when the bean is not available or defined while auto-wired in another class.

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘zoo’: Unsatisfied dependency expressed through field ‘lion’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.yawintutor.Lion’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

If the root cause exception is displayed as No qualifying bean of type then follow the link below to resolve this exception.

NoSuchBeanDefinitionException: No qualifying bean of type

NoSuchBeanDefinitionException: No bean named available

This exception happens when you try to access a bean that is not available or is not defined in the spring boot context.

Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘lion1’ available

If the root cause exception is displayed as No qualifying bean of type then follow the link below to resolve this exception.

NoSuchBeanDefinitionException: No bean named available

BeanCurrentlyInCreationException: Error creating bean with name: Requested bean is currently in creation

This exception happens when two beans are in circular dependences with each other.

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘department’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Department.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘lion’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Lion.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘tiger’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Tiger.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘lion’: Requested bean is currently in creation: Is there an unresolvable circular reference?

If the root cause exception is displayed as Requested bean is currently in creation then follow the link below to resolve this exception.

BeanCurrentlyInCreationException: Error creating bean with name: Requested bean is currently in creation

NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found

This exception occurs when the bean is auto-wired that matches two or more loaded beans in the spring boot application context.

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘zoo’: Unsatisfied dependency expressed through field ‘animal’; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘com.yawintutor.Animal’ available: expected single matching bean but found 2: lion,tiger

If the root cause exception is displayed as expected single matching bean but found then follow the link below to resolve this exception.

NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found

BeanInstantiationException: Failed to instantiate: No default constructor found

If the default constructor is not found while auto-wiring the bean, the exception below will be thrown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘department’ defined in file [SpringBootBean/target/classes/com/yawintutor/Department.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yawintutor.Department]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.yawintutor.Department.

If the root cause exception is displayed as No default constructor found then follow the link below to resolve this exception.

BeanInstantiationException: Failed to instantiate: No default constructor found

BeanInstantiationException: Failed to instantiate: Constructor threw exception

If the default constructor throws an exception while auto-wiring the bean, the exception below will be thrown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘department’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Department.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yawintutor.Department]: Constructor threw exception; nested exception is java.lang.NullPointerException

If the root cause exception is displayed as Constructor threw exception then follow the link below to resolve this exception.

BeanInstantiationException: Failed to instantiate: Constructor threw exception

BeanInstantiationException: Failed to instantiate: Factory method threw exception

If the bean is not available, try to create and load using the abstract class name and bean factory. The beans are not going to instantiate. In this case, the exception below will be thrown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘animal’ defined in class path resource [com/yawintutor/SpringConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yawintutor.AbstractAnimal]: Factory method ‘animal’ threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘abstractAnimal’ available

If the root cause exception is displayed as Factory method threw exception then follow the link below to resolve this exception.

BeanInstantiationException: Failed to instantiate: Factory method threw exception

If you find some other type of BeanCreationException, please add it to the comments section, we will provide you with the solution.

What is Bean Creation exception?-error creating bean with name

error creating bean with name,What is Bean Creation exception?,What is unsatisfied dependency exception?,Is org Springframework beans factory,NoSuchBeanDefinitionException?,How do I create a new bean?,error creating bean with name defined in file,error creating bean,with name spring boot,error creating bean with name'configurationpropertiesbeans',

error creating bean with name,What is Bean Creation exception?,What is unsatisfied dependency exception?,Is org Springframework beans factory,NoSuchBeanDefinitionException?,How do I create a new bean?,error creating bean with name defined in file,error creating bean,with name spring boot,error creating bean with name’configurationpropertiesbeans’,

If you’re mistreatment the Spring framework in your Java application and obtaining this error throughout startup it means Spring isn’t able to initialize the bean X and add it into its application context, Why? There might be multiple reasons sort of a typographical error on the spring bean name. Let’s take a more in-depth examine the stack trace to search out out the $64000 reason:

BeanInstantiationException: couldn’t instantiate bean category [X]: No default builder found; nested exception is java.lang.NoSuchMethodException: X.()

Here X is that the category, that is asserted as Spring bean. The error clearly says that the default builder isn’t gift at school X.

By default, Spring can attempt to instantiate beans by job the default or no-argument constructor and if it does not notice the default, no-argument builder then it’s ineffectual to initialize the bean and thus it throws the BeanInstantiationException during startup,additionally appended into stack trace as NoSuchMethodException.

If you bear in mind, Java by default adds a default builder in each category however several programmers do not know that it solely will that if you do not have any builder within the category if by any probability you’ve got outlined a builder that takes a parameter, then Java won’t add it.

This is conjointly one among the explanations I suggest always add a default builder within the Java category, notwithstanding whether or not you’ve got additional constructors or not. Java permits builder overloading and you must cash in of that.

I conjointly counsel you undergo a comprehensive Spring on-line coaching course to grasp however Spring works, however it instantiates objects, wherever will it keep the item reference, dependency injection, IOC instrumentation, and far additional.

If you wish a recommendation then I counsel you be part of one among the courses during this list of best Spring courses for Java developers. It’s one among the foremost up-to-date resources to be told in Spring and covers Spring five.0 and Reactive Programming yet. 

error creating bean with name,What is Bean Creation exception?,What is unsatisfied dependency exception?,Is org Springframework beans factory,NoSuchBeanDefinitionException?,How do I create a new bean?,error creating bean with name defined in file,error creating bean,with name spring boot,error creating bean with name'configurationpropertiesbeans',

error creating bean with name,What is Bean Creation exception?,What is unsatisfied dependency exception?,Is org Springframework beans factory,NoSuchBeanDefinitionException?,How do I create a new bean?,error creating bean with name defined in file,error creating bean,with name spring boot,error creating bean with name'configurationpropertiesbeans',

error creating bean with name,What is Bean Creation exception?,What is unsatisfied dependency exception?,Is org Springframework beans factory,NoSuchBeanDefinitionException?,How do I create a new bean?,error creating bean with name defined in file,error creating bean,with name spring boot,error creating bean with name'configurationpropertiesbeans',

Btw, if you’re mistreatment XML based mostly configuration then certify you’re mistreatment the proper builder on your config.

. It does not say something concerning the error, that is why you wish to appear at the nested exception to search out the particular cause.

For example, during this case, the nested error was BeanInstantiationException, that indicates the internal representation of a bean unsuccessful.

You should continuously concentrate to elaborated stack trace because it conjointly carries the violative bean category and reason like during this case, it absolutely was making an attempt to instantiate bean by invoking default builder and could not notice it.

By observing the error, you’ll conclude that whether or not you wish to feature a default builder or Spring is invoking a wrong constructor, which implies a missing config somehow.

Sometimes BeanInstantiationException is conjointly throwing in Spring isn’t able to notice the bean category within the classpath. that point you’ll see either NoClassDefFoundError or ClassNotFoundException as a nested exception within the stack trace.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error creating acrobat printer style
  • Error createservice error 0x421
  • Error createprocess error 216
  • Error createbot failed cs go
  • Error create thumbnail image joomshopping

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии