Error creating bean with name router function mapping

Пытаюсь запустить первое приложение Spring MVC и не могу понять ошибку. import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import...

Пытаюсь запустить первое приложение Spring MVC и не могу понять ошибку.

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;


public class SpringWebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {ApplicationContextConfig.class};
        //return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {

        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }


}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;


@Configuration
@ComponentScan(basePackages = { "com.vokmar" }) 
@EnableWebMvc
public class ApplicationContextConfig implements WebMvcConfigurer {

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new 
        InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
            return viewResolver;
    }


}
import java.util.Locale;
import javax.enterprise.inject.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class HelloWorldController {

    @RequestMapping(value = "/boqpv", method = RequestMethod.GET)
    public String home() {
        return "home";
    }

}

Как решить эту проблему?

         Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'routerFunctionMapping' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.function.support.RouterFunctionMapping]: Factory method 'routerFunctionMapping' threw exception; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException|#]
              Context initialization failed
            org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'routerFunctionMapping' defined in org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.function.support.RouterFunctionMapping]: Factory method 'routerFunctionMapping' threw exception; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
                at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:645)
                at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:625)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
                at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
                at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
                at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
                at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
                at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
                at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
                at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
                at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
                at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
                at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
                at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
                at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:5043)
                at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:592)
                at org.apache.catalina.core.StandardContext.start(StandardContext.java:5612)
                at com.sun.enterprise.web.WebModule.start(WebModule.java:540)
                at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
                at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
                at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
                at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2044)
                at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1690)
                at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
                at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
                at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
                at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352)
                at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500)
                at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
                at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:540)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:536)
                at java.security.AccessController.doPrivileged(Native Method)
                at javax.security.auth.Subject.doAs(Subject.java:360)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:535)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:566)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:558)
                at java.security.AccessController.doPrivileged(Native Method)
                at javax.security.auth.Subject.doAs(Subject.java:360)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:557)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1465)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:110)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1847)
                at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1723)
                at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
                at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
                at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:190)
                at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
                at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
                at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
                at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
                at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
                at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
                at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
                at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
                at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
                at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
                at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
                at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
                at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
                at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
                at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
                at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
                at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
                at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
                at java.lang.Thread.run(Thread.java:748)
            Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.function.support.RouterFunctionMapping]: Factory method 'routerFunctionMapping' threw exception; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
                at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
                at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:640)
                ... 67 more


    ----------
       ...
    <properties>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <failOnMissingWebXml>false</failOnMissingWebXml>
            <jakartaee>8.0</jakartaee>
            <spring.version>5.2.1.RELEASE</spring.version>
            <jstl.version>1.2.1</jstl.version>
            <tld.version>1.1.2</tld.version>
            <servlets.version>3.1.0</servlets.version>
            <jsp.version>2.3.1</jsp.version>

        </properties>
    ....

Помогите, кто может…

Содержание

  1. BeanCreationException: Error creating bean with name
  2. NoSuchBeanDefinitionException: No qualifying bean of type
  3. NoSuchBeanDefinitionException: No qualifying bean of type
  4. NoSuchBeanDefinitionException: No bean named available
  5. NoSuchBeanDefinitionException: No bean named available
  6. BeanCurrentlyInCreationException: Error creating bean with name: Requested bean is currently in creation
  7. BeanCurrentlyInCreationException: Error creating bean with name: Requested bean is currently in creation
  8. NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found
  9. NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found
  10. BeanInstantiationException: Failed to instantiate: No default constructor found
  11. BeanInstantiationException: Failed to instantiate: No default constructor found
  12. BeanInstantiationException: Failed to instantiate: Constructor threw exception
  13. BeanInstantiationException: Failed to instantiate: Constructor threw exception
  14. BeanInstantiationException: Failed to instantiate: Factory method threw exception
  15. BeanInstantiationException: Failed to instantiate: Factory method threw exception
  16. 2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]
  17. 1) No default constructor on Spring Bean
  18. 2) Spring Bean dependent on third party library

BeanCreationException: Error creating bean with name

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:

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.

Источник

2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]

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.

Источник

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

What is the issue?

In our spring boot application on controller level when we added same request mapping for multiple methods, we got into this issue. Following is the issue in details:

The error message

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'springController' method 
public java.lang.String no.mentormedier.migration.controller.SpringController.home(org.springframework.ui.Model)
to { /}: There is already 'homePageController' bean method

How to get the error?

In spring request mapping it is not allowed to have same URL map on multiple methods. The @RequestMapping annotation will simply not allow us to do that. The following code will run into this error:

    @RequestMapping({"/"})
    public String home(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "home";
    }

    @RequestMapping({"/"})
    public String newhome(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "newhome";
    }

The solution

We will have to have different request mapping for different methods. We can simply change the request mapping with something unique and that will solve this issue:

    @RequestMapping({"/"})
    public String home(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "home";
    }

    @RequestMapping({"/new"})
    public String newhome(Model model) {
        model.addAttribute("targetEnv", activeProfile);
        return "newhome";
    }

K0T

2 / 2 / 1

Регистрация: 28.10.2013

Сообщений: 114

1

08.06.2017, 21:10. Показов 25875. Ответов 5

Метки нет (Все метки)


Доброго времени суток, столкнулся с такой вот ошибкой, не знаю что делать, прошу вас о помощи.
При загрузке стартовой страницы всё нормально, но вот при переходе на другую страницу, в моем случаи http://localhost:8080/list вылетает «это»
99% — проблема в аннотации @EnableWebMvc, при удалении этой аннотации — всё норм(но без неё не подгружаются никакие ресурсы для jsp страницы), при её добавлении с ресурсами всё ок, но получаю ошибку при переходе на другую страницу

WebConfig

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.spring.configuration;
 
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
 
import javax.sql.DataSource;
import java.util.Properties;
 
@Configuration
@EnableWebMvc  //здесь
@EnableTransactionManagement
@ComponentScan(
        basePackages = { "com.spring" },
        excludeFilters = { @ComponentScan.Filter(
                type = FilterType.ANNOTATION,
                value = Configuration.class)}
)
@PropertySource(value = {"classpath:application.properties"})
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Autowired
    private Environment environment;
 
    @Override  //ну или здесь
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
 
    @Bean
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
 
        return resolver;
    }
 
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan("com.spring.model");  //new String[] { "com.spring.model" }
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }
 
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
 
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put(
                "log4j.logger.org.hibernate.SQL",
                environment.getRequiredProperty("log4j.logger.org.hibernate.SQL")
        );
        properties.put(
                "log4j.logger.org.hibernate.type",
                environment.getRequiredProperty("log4j.logger.org.hibernate.type")
        );
        return properties;
    }
 
    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }
}

pom.xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>
 
    <groupId>com</groupId>
    <artifactId>Traveler</artifactId>
    <version>1.0</version>
 
    <name>Traveler</name>
 
    <properties>
        <springframework.version>4.3.8.RELEASE</springframework.version>
        <hibernate.version>5.2.9.Final</hibernate.version>
    </properties>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
    <dependencies>
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0-b05</version>
        </dependency>
 
        <!-- JSTL -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
 
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
 
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
 
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
    </dependencies>
 
 
 
</project>

Controller

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.spring.controller;
 
import com.spring.configuration.WebConfiguration;
import com.spring.model.Place;
import com.spring.model.User;
import com.spring.service.PlaceService;
import com.spring.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import java.util.ArrayList;
 
@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView home() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", new User());
        modelAndView.setViewName("index");
 
        return modelAndView;
    }
 
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public ModelAndView reg(@ModelAttribute("user") User user) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(WebConfiguration.class);
        ModelAndView modelAndView = new ModelAndView();
        UserService service = (UserService) context.getBean("userService");
 
        modelAndView.setViewName("registration");
        modelAndView.addObject("user", user);
        service.saveUser(user);
 
        context.close();
        return modelAndView;
    }
 
    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public ModelAndView authorization(@ModelAttribute("user") User user) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(WebConfiguration.class);
        ModelAndView modelAndView = new ModelAndView();
        UserService service = (UserService) context.getBean("userService");
 
        modelAndView.addObject("user", user);
 
        if (service.findByLogin(user.getLogin()) != null)
        {
            if (service.findByLogin(user.getLogin()).getPassword().equals(user.getPassword()))
                modelAndView.setViewName("authorization");
            else
                modelAndView.setViewName("authorizeFail");
        }
        else
        modelAndView.setViewName("authorizeFail");
 
        context.close();
        return modelAndView;
    }
 
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(@ModelAttribute("user") User user, @ModelAttribute("list") ArrayList<Place> list) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(WebConfiguration.class);
        PlaceService service = (PlaceService) context.getBean("placeService");
 
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        list = (ArrayList<Place>) service.findAllPlaces();
        modelAndView.addObject("list", list);
        modelAndView.setViewName("list");
 
        context.close();
        return modelAndView;
    }
}

Проект на Git
https://github.com/Cat95/Traveler

Помогите пожалуйста, сильно не критикуйте, мой первый web проект и я много чего не знаю(

Миниатюры

Error creating bean with name 'resourceHandlerMapping'
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт Java

3636 / 2968 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

08.06.2017, 21:25

2

стэктрэйс полностью выложи нафиг твои скриншоты не нужны



0



2 / 2 / 1

Регистрация: 28.10.2013

Сообщений: 114

08.06.2017, 21:31

 [ТС]

3

HTTP Status 500 – Internal Server Error

Type Exception Report

Message Request processing failed; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name ‘resourceHandlerMapping’ defined in org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationExcepti on: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is org.springframework.beans.factory.BeanInitializati onException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletExceptio n: Request processing failed; nested exception is org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name ‘resourceHandlerMapping’ defined in org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationExcepti on: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is org.springframework.beans.factory.BeanInitializati onException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy
org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet .java:635)
org.springframework.web.servlet.FrameworkServlet.s ervice(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet .java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)
Root Cause

org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name ‘resourceHandlerMapping’ defined in org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationExcepti on: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is org.springframework.beans.factory.BeanInitializati onException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy
org.springframework.beans.factory.support.Construc torResolver.instantiateUsingFactoryMethod(Construc torResolver.java:599)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateUsingFactory Method(AbstractAutowireCapableBeanFactory.java:117 3)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:1067)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:513)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:483)
org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:3 06)
org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:230)
org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:302 )
org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:761)
org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:866)
org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:542)
org.springframework.context.annotation.AnnotationC onfigApplicationContext.<init>(AnnotationConfigApp licationContext.java:84)
com.spring.controller.HomeController.list(HomeCont roller.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHa ndlerMethod.doInvoke(InvocableHandlerMethod.java:2 05)
org.springframework.web.method.support.InvocableHa ndlerMethod.invokeForRequest(InvocableHandlerMetho d.java:133)
org.springframework.web.servlet.mvc.method.annotat ion.ServletInvocableHandlerMethod.invokeAndHandle( ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.invokeHandlerMeth od(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.handleInternal(Re questMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.Abstrac tHandlerMethodAdapter.handle(AbstractHandlerMethod Adapter.java:85)
org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet .java:635)
org.springframework.web.servlet.FrameworkServlet.s ervice(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet .java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)
Root Cause

org.springframework.beans.BeanInstantiationExcepti on: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is org.springframework.beans.factory.BeanInitializati onException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy
org.springframework.beans.factory.support.SimpleIn stantiationStrategy.instantiate(SimpleInstantiatio nStrategy.java:189)
org.springframework.beans.factory.support.Construc torResolver.instantiateUsingFactoryMethod(Construc torResolver.java:588)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateUsingFactory Method(AbstractAutowireCapableBeanFactory.java:117 3)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:1067)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:513)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:483)
org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:3 06)
org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:230)
org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:302 )
org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:761)
org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:866)
org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:542)
org.springframework.context.annotation.AnnotationC onfigApplicationContext.<init>(AnnotationConfigApp licationContext.java:84)
com.spring.controller.HomeController.list(HomeCont roller.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHa ndlerMethod.doInvoke(InvocableHandlerMethod.java:2 05)
org.springframework.web.method.support.InvocableHa ndlerMethod.invokeForRequest(InvocableHandlerMetho d.java:133)
org.springframework.web.servlet.mvc.method.annotat ion.ServletInvocableHandlerMethod.invokeAndHandle( ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.invokeHandlerMeth od(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.handleInternal(Re questMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.Abstrac tHandlerMethodAdapter.handle(AbstractHandlerMethod Adapter.java:85)
org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet .java:635)
org.springframework.web.servlet.FrameworkServlet.s ervice(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet .java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)



0



2 / 2 / 1

Регистрация: 28.10.2013

Сообщений: 114

08.06.2017, 21:35

 [ТС]

4

Продолжение, всё сразу не влезло.

Root Cause

org.springframework.beans.factory.BeanInitializati onException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy
org.springframework.web.servlet.config.annotation. ResourceHandlerRegistry.getHandlerMapping(Resource HandlerRegistry.java:150)
org.springframework.web.servlet.config.annotation. WebMvcConfigurationSupport.resourceHandlerMapping( WebMvcConfigurationSupport.java:452)
org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration$$EnhancerBySpringCGL IB$$5f549bfb.CGLIB$resourceHandlerMapping$32(<gene rated>)
org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration$$EnhancerBySpringCGL IB$$5f549bfb$$FastClassBySpringCGLIB$$992f089d.inv oke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke Super(MethodProxy.java:228)
org.springframework.context.annotation.Configurati onClassEnhancer$BeanMethodInterceptor.intercept(Co nfigurationClassEnhancer.java:358)
org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration$$EnhancerBySpringCGL IB$$5f549bfb.resourceHandlerMapping(<generated>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.beans.factory.support.SimpleIn stantiationStrategy.instantiate(SimpleInstantiatio nStrategy.java:162)
org.springframework.beans.factory.support.Construc torResolver.instantiateUsingFactoryMethod(Construc torResolver.java:588)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateUsingFactory Method(AbstractAutowireCapableBeanFactory.java:117 3)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:1067)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:513)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:483)
org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:3 06)
org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:230)
org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:302 )
org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:761)
org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:866)
org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:542)
org.springframework.context.annotation.AnnotationC onfigApplicationContext.<init>(AnnotationConfigApp licationContext.java:84)
com.spring.controller.HomeController.list(HomeCont roller.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHa ndlerMethod.doInvoke(InvocableHandlerMethod.java:2 05)
org.springframework.web.method.support.InvocableHa ndlerMethod.invokeForRequest(InvocableHandlerMetho d.java:133)
org.springframework.web.servlet.mvc.method.annotat ion.ServletInvocableHandlerMethod.invokeAndHandle( ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.invokeHandlerMeth od(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.handleInternal(Re questMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.Abstrac tHandlerMethodAdapter.handle(AbstractHandlerMethod Adapter.java:85)
org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet .java:635)
org.springframework.web.servlet.FrameworkServlet.s ervice(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet .java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)
Root Cause

java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy
org.springframework.web.context.support.WebApplica tionObjectSupport.getWebApplicationContext(WebAppl icationObjectSupport.java:112)
org.springframework.web.context.support.WebApplica tionObjectSupport.getServletContext(WebApplication ObjectSupport.java:128)
org.springframework.web.servlet.resource.ResourceH ttpRequestHandler.initContentNegotiationStrategy(R esourceHttpRequestHandler.java:306)
org.springframework.web.servlet.resource.ResourceH ttpRequestHandler.afterPropertiesSet(ResourceHttpR equestHandler.java:268)
org.springframework.web.servlet.config.annotation. ResourceHandlerRegistry.getHandlerMapping(Resource HandlerRegistry.java:147)
org.springframework.web.servlet.config.annotation. WebMvcConfigurationSupport.resourceHandlerMapping( WebMvcConfigurationSupport.java:452)
org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration$$EnhancerBySpringCGL IB$$5f549bfb.CGLIB$resourceHandlerMapping$32(<gene rated>)
org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration$$EnhancerBySpringCGL IB$$5f549bfb$$FastClassBySpringCGLIB$$992f089d.inv oke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke Super(MethodProxy.java:228)
org.springframework.context.annotation.Configurati onClassEnhancer$BeanMethodInterceptor.intercept(Co nfigurationClassEnhancer.java:358)
org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration$$EnhancerBySpringCGL IB$$5f549bfb.resourceHandlerMapping(<generated>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.beans.factory.support.SimpleIn stantiationStrategy.instantiate(SimpleInstantiatio nStrategy.java:162)
org.springframework.beans.factory.support.Construc torResolver.instantiateUsingFactoryMethod(Construc torResolver.java:588)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.instantiateUsingFactory Method(AbstractAutowireCapableBeanFactory.java:117 3)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBeanInstance(Abst ractAutowireCapableBeanFactory.java:1067)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:513)
org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:483)
org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:3 06)
org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:230)
org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:302 )
org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:761)
org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:866)
org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:542)
org.springframework.context.annotation.AnnotationC onfigApplicationContext.<init>(AnnotationConfigApp licationContext.java:84)
com.spring.controller.HomeController.list(HomeCont roller.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHa ndlerMethod.doInvoke(InvocableHandlerMethod.java:2 05)
org.springframework.web.method.support.InvocableHa ndlerMethod.invokeForRequest(InvocableHandlerMetho d.java:133)
org.springframework.web.servlet.mvc.method.annotat ion.ServletInvocableHandlerMethod.invokeAndHandle( ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.invokeHandlerMeth od(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotat ion.RequestMappingHandlerAdapter.handleInternal(Re questMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.Abstrac tHandlerMethodAdapter.handle(AbstractHandlerMethod Adapter.java:85)
org.springframework.web.servlet.DispatcherServlet. doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet. doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.p rocessRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.d oGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet .java:635)
org.springframework.web.servlet.FrameworkServlet.s ervice(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet .java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilt er(WsFilter.java:53)

Добавлено через 1 минуту
Это из сервер лога

08-Jun-2017 21:28:26.390 WARNING [http-nio-8080-exec-2] org.springframework.context.annotation.AnnotationC onfigApplicationContext.refresh Exception encountered during context initialization — cancelling refresh attempt: org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name ‘resourceHandlerMapping’ defined in org.springframework.web.servlet.config.annotation. DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationExcepti on: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is org.springframework.beans.factory.BeanInitializati onException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/]], resolvers=[org.springframework.web.servlet.resource.PathResou rceResolver@42947e2]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationC onfigApplicationContext@489ea798: startup date [Thu Jun 08 21:28:25 EEST 2017]; root of context hierarchy



0



Эксперт Java

3636 / 2968 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

08.06.2017, 21:39

5

Цитата
Сообщение от K0T
Посмотреть сообщение

AbstractApplicationContext context = new AnnotationConfigApplicationContext(WebConfiguratio n.class);
* * * * PlaceService service = (PlaceService) context.getBean(«placeService»);

про autowired конечно не слышал?
вообщ лень вникать, но скорее всего конфиг кривой, переходи на спринг бут



1



K0T

2 / 2 / 1

Регистрация: 28.10.2013

Сообщений: 114

09.06.2017, 00:05

 [ТС]

6

Это мой первый проект с использованием Spring и Hibernate и я скорее всего о большинстве вещей не слышал)
Я тоже так думаю) ну, и нам том спасибо)

Добавлено через 42 минуты

Java
1
AbstractApplicationContext context = new AnnotationConfigApplicationContext(WebConfiguration.class);

Может ли быть проблема в этом месте?

Добавлено через 1 час 39 минут
Решил проблемы сам.
Если кому интересно:

Java
1
AbstractApplicationContext context = new AnnotationConfigApplicationContext(WebConfiguration.class)

В виду отсутствия опыта, писал этот г***код только для того чтобы достать бин «placeService», убрал к чертям эту строку и всё использование контекста в своем контроллере, а чтобы получить «сервис» прописал в начале контроллера

Java
1
2
@Resource(name="placeService")    //имя бина "сервис"
private PlaceService placeService

и с ним уже работал.



0



Issue

I am having a hard time staring up my server with spring. I looked up similar errors to mine and it seemed it had to do with the way I used RequestMapping. Despite having tried various methods to define my routes, I still can’t figure out what seems to be the problem. Any ideas?

This is my error message:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'qualificationRepository' defined in com.salay.christophersalayportfolio.repositories.QualificationRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.salay.christophersalayportfolio.models.ProgrammingLanguage.dissertation in com.salay.christophersalayportfolio.models.Dissertation.programmingLanguages
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'qualificationRepository' defined in com.salay.christophersalayportfolio.repositories.QualificationRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.salay.christophersalayportfolio.models.ProgrammingLanguage.dissertation in com.salay.christophersalayportfolio.models.Dissertation.programmingLanguages

My TaskController

import com.salay.christophersalayportfolio.models.Task;
import com.salay.christophersalayportfolio.repositories.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(path = "/api/v1/tasks")
public class TaskController {

    @Autowired
    private TaskRepository taskRepository;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody String add(@RequestBody Task task) {
        taskRepository.save(task);
        return "Successfully saved the task to the database.";
    }

    @RequestMapping(value = "/{id/", method = RequestMethod.GET)
    public Task getById(@PathVariable int id){

        Optional<Task> task = taskRepository.findById(id);

        if(!task.isPresent()){
            throw new NullPointerException();
        }
        else {
            return task.get();
        }
    }

    @RequestMapping(value = "/all/", method = RequestMethod.GET)
    public List<Task> getAll() {
        return taskRepository.findAll();
    }

}

My ProgrammingLanguagesController:

package com.salay.christophersalayportfolio.controllers;

import com.salay.christophersalayportfolio.models.ProgrammingLanguage;
import com.salay.christophersalayportfolio.repositories.ProgrammingLanguageRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(path = "/api/v1/programmingLanguages")
public class ProgrammingLanguageController {

    @Autowired
    private ProgrammingLanguageRepositories plRepository;

    @RequestMapping( value= "/add", method = RequestMethod.POST)
    public @ResponseBody String add(@RequestBody ProgrammingLanguage pl){
        plRepository.save(pl);
        return "This programming language has been successfully saved";
    }


    @RequestMapping( value = "/{id}/", method = RequestMethod.GET)
    public ProgrammingLanguage getById(@PathVariable int id){
        Optional<ProgrammingLanguage> pl = plRepository.findById(id);

        if( !pl.isPresent()){
            throw new NullPointerException();
        }
        else {
            return pl.get();
        }
    }

    @RequestMapping( value = "/all", method = RequestMethod.GET)
    public List<ProgrammingLanguage> getAll(){
        return plRepository.findAll();
    }
}

Below are my entities:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class ProgrammingLanguage {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    public String name;
    public String image;
}
import javax.persistence.*;
import java.util.Set;

@Entity
public class Dissertation {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private int qualificationId;
    public String title;

    @OneToMany(mappedBy="dissertation")
    public Set<ProgrammingLanguage> programmingLanguages;
    public Set<Tool> tools;
}
package com.salay.christophersalayportfolio.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private int experienceId;
    private int projectId;
    public String description;
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private int experienceId;
    private int projectId;
    public String description;
}
import javax.persistence.*;
import java.util.Set;

@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    public String name;
    public String description;
    public String client;

    @OneToMany(mappedBy = "project")
    public Set<ProgrammingLanguage> programmingLanguages;

    @OneToMany(mappedBy = "project")
    public Set<Tool> tools;

    @OneToMany(mappedBy = "project")
    public Set<String> images;

    @OneToMany(mappedBy = "project")
    public Set<Task> tasks;
}

My pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.salay</groupId>
    <artifactId>christopher-salay-portfolio</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>christopher-salay-portfolio</name>
    <description>Back-end application for my portfolio</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>8.3.1.jre14-preview</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Solution

The problem is not in your request mapping, your app does not start because of an issue in your entity mapping, please double check your mappings as stated in your error: mappedBy reference an unknown target entity

org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.salay.christophersalayportfolio.models.ProgrammingLanguage.dissertation in com.salay.christophersalayportfolio.models.Dissertation.programmingLanguages

It seems your class com.salay.christophersalayportfolio.models.ProgrammingLanguage does not have a property named dissertation

Otherwise, share your model to take a look!

Answered By — arturo.bhn

See above. JAXB is not included with Java 9 and above (but you can add it as an external dependency).

Hi dsyer! I have an error about creating bean with name ‘springSecurityFilterChain’. this error is below:

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
2020-12-22T11:04:48.076+0700 ERROR Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘springSecurityFilterChain’ defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method ‘springSecurityFilterChain’ threw exception; nested exception is java.lang.IllegalStateException: At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. Typically this is done by exposing a SecurityFilterChain bean or by adding a @configuration that extends WebSecurityConfigurerAdapter. More advanced users can invoke WebSecurity.addSecurityFilterChainBuilder directly.

I fixed this by adding @configuration in CustomSecurityConfigurerAdapter class that extends WebSecurityConfigurerAdapter, but it’s not working. Pls, help me fix this ! Thank you very much

In this post, we will see the possible reasons and fixes for the ‘Error creating bean with name entityManagerFactory defined in class path resource : Invocation of init method failed’ error.

Spring Data JPA Interview Questions and Answers

You may encounter this error if you are using JPA in your application. This error indicates that we have something wrong in the database configuration and the EntityManagerFactory is not getting created. There can be multiple reasons for this exception.

Note – Try to look into the bottom of error stack trace that will help you to figure out the exact root cause of this exception.

Let’s see how to fix the Error creating bean with name entityManagerFactory defined in class path resource : Invocation of init method failed error.

1. Check your database configuration. Make sure you have provided proper database details(check for the database name, username, password, and other configuration). For example, if we provide the wrong database name that doesn’t exist in MySQL DB we will get this error. Also if we pro

spring.datasource.url=jdbc:mysql://localhost:3306/springbootcrudexample
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
server.port = 9091

Note – For Postgres and Oracle database configuration check this post.

2. Make sure you are using @ID annotation with the primary key field in your entity class. For example below code will throw org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ error.

@Entity
public class Student implements Serializable {
    //@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "roll_number")
    private String rollNumber;

    @Column(name = "university")
    private String university;
}

3. If you have defined dialect in application.properties file, make sure you are using the correct dialect.

For example, below will not work and throw the error.

spring.jpa.properties.hibernate.dialect =  org.hibernate.dialect.MySQL9Dialect

The dialect name should org.hibernate.dialect.MySQL8Dialect

4. If you are trying to connect remote databases using some IPs, make sure it is up and running and accessible.

5. If you have an older application(not using Spring Boot and Spring Data JPA) try to add the below maven dependency in pom.xml.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

and

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.3.Final</version>
</dependency>

6. If you are using Java 9, you may end up with org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ error.

Add the below dependency in your pom.xml.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

7. You may encounter this exception if you have association mapping between entities. Make sure you are using proper mapping for your entities.

  • One To One unidirectional mapping – See an example here.
  • One To One Bidirectional mapping – See an example here.
  • One To Many unidirectional mapping – See an example here.
  • One To Many Bidirectional mapping – See an example here.
  • One To Many Bidirectional Using Join Table(Third table) – See an example here.
  • Many To one unidirectional mapping – See an example here.
  • Many To Many mapping – See an example here.

8. Go through the error stack trace and try to find out the root cause.

For example, if we have the wrong dialect value configured we can get it in the exception stack trace.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at com.netsurfingzone.main.SpringMain.main(SpringMain.java:14) [classes/:na]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
… 17 common frames omitted
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQL9Dialect] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:156) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:239) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:183) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:170) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:164) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:74) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:51) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
… 34 common frames omitted
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQL9Dialect]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:152) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
… 44 common frames omitted
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQL9Dialect
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_251]
at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_251]
at java.lang.Class.forName0(Native Method) ~[na:1.8.0_251]
at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_251]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:130) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
… 45 common frames omitted

9. If you are using JDK 11 and higher version try to add the below dependency.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.11</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.11</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.11</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

Below source code is responsible for this exception.

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

Hope this tutorial helps to fix org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource.

Other spring data JPA examples.

  • Spring Data JPA CrudRepository findById()
  • Spring Data findById() Vs getOne()
  • Spring Data JPA JpaRepository getOne()
  • Spring Data CrudRepository saveAll() and findAll().
  • Spring Data CrudRepository existsById()
  • Spring Data JPA delete() vs deleteInBatch()
  • Spring Data JPA deleteAll() Vs deleteAllInBatch()
  • Spring Data JPA JpaRepository deleteAllInBatch()
  • Spring Data JPA deleteInBatch() Example
  • Spring Data JPA JpaRepository saveAndFlush() Example
  • Spring Data JPA CrudRepository count() Example
  • Spring Data JPA CrudRepository delete() and deleteAll()
  • Spring Data JPA CrudRepository deleteById() Example
  • CrudRepository findAllById() Example Using Spring Boot
  • Spring Data CrudRepository save() Method.
  • Sorting in Spring Data JPA using Spring Boot.
  • Spring Data JPA example using spring boot.
  • Spring Data JPA and its benefit.

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

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

  • Error creating bean with name kafkalistenercontainerfactory
  • Error creating bean with name defined in file
  • Error creating bean with name controller
  • Error creating bean with name configurationpropertiesbeans
  • Error creating aufs mount to var lib docker aufs mnt

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

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