Error creating bean with name resource handler mapping

I have an application with spring that use a JpaConfiguration class to deal with my database, and a WebAppMvcConfigurer class to deal with the front via json message. Both have an @Configuration an...

I have an application with spring that use a JpaConfiguration class to deal with my database, and a WebAppMvcConfigurer class to deal with the front via json message. Both have an @Configuration and are in the same package. I have an App class in a root package with @Configuration and @ComponentScan with my main method.

When I launch App class I get this error :

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
    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.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)
    at com.bnpp.creditauto.App.main(App.java:22)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 14 more
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:533)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 15 more

What «works» so far is delete one of the two @Configuration in either JpaConfiguration or WebAppMvcConfigurer. If i delete the @Configuration WebApp one i can interact with my database no problem, but cant access anything from my angular application.
If I delete the @Configuration in JpaConf the front part of the application works and I can access the json my Java application sends with my angular application no problem, but cant do anything with my database.

Somewhere I read to change @Configuation to @WebAppConfiguration in WebAppMvcConfigurer, it does the same as removing the @Configuration, JpaConfiguration works fine and front part doesnt work.

I checked dependencies and tried the last version without success.
I tried to change in App : @ComponentScan(basePackages = { "org.example.springproject" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
without success too, it is the same as deleting both @Configuration in Jpa and webapp

My app class :

package com.bnpp.creditauto;

@Configuration
@ComponentScan//("com.bnpp.creditauto")
public class App {

    public static void main(String[] args) {
        ...
}

JpaConfiguration class :

package com.bnpp.creditauto.config;

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class JpaConfiguration {
  ...
}

WebAppMvcConfigurer class :

package com.bnpp.creditauto.config;

@Configuration
@EnableWebMvc
public class WebAppMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

I am trying to create a rest oauth secured service using spring boot 2.0.0.M4. I am keep getting below exception. I read couple of posts related to error in creating bean with name […] but nothing worked out.I am posting here my pom.xml along with code. Please guide me if anything clicks to anybody.


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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ctl.spring</groupId>
    <artifactId>OauthSpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>OauthSpringBoot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M4</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
         <aspectj.version>1.8.10</aspectj.version>
        <maven-jar-plugin.version>2.6</maven-jar-plugin.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            </dependency>
        <dependency>
            <groupId>com.github.noraui</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.2</version>
        </dependency>
        <dependency>    
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            </dependency>

            <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
           </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    <!--    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency> -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</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>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

OauthSpringBootApplication.java

package ctl.spring.OauthSpringBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
//@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
//@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,WebMvcAutoConfiguration.class })
@ComponentScan("ctl.spring")
public class OauthSpringBootApplication {

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

EaseRestController .java

package ctl.spring.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import ctl.spring.model.User;
import ctl.spring.services.UserService;


@RestController
public class EaseRestController {

    @Autowired
    UserService userService;

    @RequestMapping(value="/hello", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public String getHello()
    {
        return "Hello World !!";
    }

    @RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
     public ResponseEntity<List<User>>  getAllUsers()
    {
        List<User> users =userService.findAllUsers();

        if(users ==null || users.size()<0)
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<List<User>>(users,HttpStatus.OK); 
    }

    @RequestMapping(value="/user/{id}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> findUser(@PathVariable String id)
       {
           User data=userService.findUserById(Integer.parseInt(id));

           if(data== null)
               return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
           else
               return new ResponseEntity<User>(data,HttpStatus.OK);
       }

      @RequestMapping(value="/createUser/", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Void> createUser(@RequestBody User user)
        {
            User dUser= userService.findUserById(Integer.parseInt(user.getId()));

            if(dUser== null) {
            userService.saveUser(user);
            return new ResponseEntity<Void>(HttpStatus.CREATED);
            }
            else
            {
                return new ResponseEntity<Void>(HttpStatus.CONFLICT);
            }
        }


}

AuthorizationServer

package ctl.spring.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static String REALM="MY_OAUTH_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
            .withClient("my-trusted-client")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .secret("secret")
            .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
            refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM+"/client");
    }

}

ResourceServer

package ctl.spring.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "my_rest_api";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http        
        .anonymous()
        .disable()
        .requestMatchers()
        .antMatchers("/users/**")
        .and()
        .authorizeRequests()
        .antMatchers("/user/**").access("hasRole('ADMIN')")
        .and()
        .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

WebSecurityConfigurerAdapter

package ctl.spring.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("bill").password("abc123").roles("ADMIN").and()
        .withUser("bob").password("abc123").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers("/oauth/token").permitAll();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}

SecurityInitializer

package ctl.spring.security;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

MethodSecurityConfig

package ctl.spring.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @SuppressWarnings("unused")
    @Autowired
    private OAuth2SecurityConfiguration securityConfig;

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }
}

Along with these I have setup AbstractAnnotationConfigDispatcherServletInitializer to add CORSFilter.

Spring Boot Error — Error creating a bean with name ‘dataSource’ defined in class path resource DataSourceAutoConfiguration

Hello guys, If you are using Spring Boot and getting errors like «Cannot determine embedded database driver class for database type NONE» or «Error creating a bean with name ‘dataSource’ defined in class path resource ataSourceAutoConfiguration» then you have come to the right place. In this article, we’ll examine different scenarios on which this Spring Boot error comes and what you can do to solve them. The general reason for this error is Spring Boot’s auto-configuration, which is trying to automatically configure a DataSource for you but doesn’t have enough information. It is automatically trying to create an instance of DataSourceAutoConfiguration bean and it’s failing.

Like other Spring frameworks errors, the stack trace looks quite messy, something which they could have improved with Spring Boot, but the gest is here are these two errors I mentioned above.

Let’s see the stacktrace looks in general:

org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.:
[INFO] org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

Btw, these errors can be intimidating if you are completely new to Spring framework. In that case, I suggest you go through a comprehensive Spring Boot course like the Learn Spring Boot by Dan Vega on Udemy. Now, let’s see some common cause of this error and what you can do to solve this problem.

1. Spring Boot Error due to Starter Dependency

Some of my friends and readers got this error even if they don’t need a Database. The main reason they were getting this error was because of starter dependency like some of they have included spring-boot-starter-data-jpa which then included hibernate-entitymanager.jar and they didn’t have additional things need to set that up.

Sometimes including incorrect Starter POM can also solve this problem like adding s pring-boot-starter-jdbc instead of spring-boot-starter-data-jpa dependency.

If you know, Spring Boot auto-configuration is triggered by JAR dependencies present in the classpath and if it pulls something which you don’t need then this type of error can come.

That’s why a good knowledge of Spring fundamentals are needed to use Spring boot correctly. If you are new into the Spring framework, I suggest you go through Learn Spring: The Certification Class by Eugen Paraschiv of Baeldung to learn Spring 5 and Spring Boot 2 from scratch, in a guided, code-focused way

2. Due to Missing Dependency

Sometimes you do need a database but you forgot to include the driver JAR file into the classpath, which can also cause this error. For example, you have specified the following properties in the application.propertie s, spring boots configuration file but didn’t include the corresponding MySQL JDBC driver into the classpath

spring.datasource.url = jdbc:mysql://localhost/test
spring.datasource.driver-class-name= com.mysql.jdbc.Drive r

In order to solve this error, either you need to include the correct Starter POM dependency or manually add the MySQL JDBC JAR file into the classpath. If you are interested, you can see this tutorial to learn more about how to connect a Java application to a database using a MySQL database in this tutorial.

3. Due to Missing Configuration in Application.properties

Spring Boot is good at configuring in-memory Databases like H2, HSQLDB, Derby, etc and it can configure them by just adding their JAR files into the classpath but for others, you need to give Spring Boot additional details like URL, DriverClass name, etc.

You can do that by adding some properties to application.properties file with the s pring.datasource prefix, as shown in following example:

spring.datasource.url = jdbc:mysql://localhost/abc
spring.datasource.name=testme
spring.datasource.username=xxxx
spring.datasource.password=xxxx
spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.jpa.database=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

This will provide the Spring Boot auto-configuration component to configure the database for you. If you want to learn more about how auto-configuration works in Spring Boot, I suggest you go through a comprehensive Spring boot course like Spring Boot: Efficient Development, Configuration, and Deployment course on Pluralsight, which will also teach you the details behind @EnableAutoConfiguration by writing your own auto configurations.

4. Exclude DataSourceAutoConfiguration

Sometimes excluding DataSourceAutoConfigution can also solve this problem, especially if you don’t need Database. This will prevent Spring Boot from automatically configuration database and there won’t be any error. You can disable auto-configuration for certain classes by using the exclude Attribute of @EnableAutoConfiguration annotation of Spring Boot as shown below:

You can even exclude more than one classes using exclude attribute with @EnableAutoConfiguration as shown below:

That’s all about how to solve «Cannot determine embedded database driver class for database type NONE» or «Error creating a bean with name ‘dataSource’ defined in class path resource DataSourceAutoConfiguration» problem. In most of the cases, it is because of auto-configuration doesn’t have enough details require to configure Database but sometimes it’s also the accidental trigger of database auto-configuration which can be disabled using exclude attribute of @EnableAutoConfiguration annotation.

Btw, if you want to learn Spring Boot in depth, here are some useful resources for your learning:

Other Java and Spring Boot articles you may like

  • 5 Spring Boot Features Every Java Developer Should Know (features)
  • Top 5 Free Courses to learn Spring and Spring Boot (courses)
  • 15 Spring Boot Interview Questions for Java developers (questions)
  • 5 Course to Master Spring Boot online (courses)
  • 10 Things Java Developer should learn (goals)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 10 Tips to become a better Java developer (tips)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)
  • Top 5 Spring Boot Annotations Java Developers should know (annotations)
  • 5 books to learn Spring Boot and Spring Cloud (books)
  • 5 courses to learn Spring Boot in depth ( courses)
  • 21 Skills Java Developers Can Learn to Enhance heir profile (skills)

Thanks for reading this article so far. If you like my explanation and solution of this Spring Boot error then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. — If you are interested in learning Spring Boot but looking for a free course to start with then I suggest you check the Free Introducing Spring Boot course on Udemy to kick start your journey into the beautiful world of Spring.

Источник

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



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

The spring boot exception IllegalStateException: Ambiguous mapping. Cannot map method occurs when two methods in the rest controller class are configured with the same request mapping url. Two methods in the rest controller class should not be configured using the same url. The exception will be shown as BeanCreationException: Error creating bean with name ‘requestMappingHandlerMapping’ defined in class path resource in spring boot application.

The ambiguous mapping is determined on the basis of two factors, the request mapping url and the request mapping method. The same url can be configured with two different request mapping methods, GET and POST.

The rest controller can not configure the same url for two different methods, as it can not distinguish which method should be called when a request is received. The spring boot framework will not be able to create the bean controller if two methods are configured with the same url in the controller class.This will throw “There is already ‘Controller’ bean method Controller#method() mapped.” exception

Exception

The exception stack trace will look like the one below. The exception “Ambiguous mapping. Can not map method” will be shown in the console window when the application starts loading the bean controller.

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 'testController' method 
com.test.TestController#helloworld()
to { /welcome}: There is already 'testController' bean method
com.test.TestController#welcomepage() mapped.
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
	at com.test.SpringHelloWorldJspApplication.main(SpringHelloWorldJspApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'testController' method 
com.test.TestController#helloworld()
to { /welcome}: There is already 'testController' bean method
com.test.TestController#welcomepage() mapped.
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.validateMethodMapping(AbstractHandlerMethodMapping.java:633) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:600) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:318) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.registerHandlerMethod(RequestMappingHandlerMapping.java:350) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.registerHandlerMethod(RequestMappingHandlerMapping.java:67) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lambda$detectHandlerMethods$1(AbstractHandlerMethodMapping.java:288) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:1.8.0_101]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:286) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(AbstractHandlerMethodMapping.java:258) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:217) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:205) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:171) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	... 16 common frames omitted

Root Cause

The rest controller uniquely identifies the request on the basis of two factors, the request mapping url and the request mapping method. The rest controller can not configure the same url for two separate methods, as it can not distinguish which method should be used when a request is received.

If two methods are configured with the same url in the controller class, the spring boot framework will not be able to create the bean controller. The spring boot framework will throw “BeanCreationException: Error creating bean with name ‘requestMappingHandlerMapping’ defined in class path resource” error.

How to reproduce this issue

If you create two methods with the same request mapping url and the same request mapping method in the rest controller class, the spring boot application can not map the url to the methods. The “Ambiguous Mapping. Cannot map the ‘Controller’ method” error will be thrown in the spring boot framework.

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {

	@RequestMapping("/welcome")
	public ModelAndView welcomepage() {
		return new ModelAndView("welcome");
	}

	@RequestMapping("/welcome")
	public ModelAndView helloworld() {
		return new ModelAndView("welcome");
	}
}

Solution 1

If two methods contains the same request mapping url configured in a rest controller class, change one url. This will distinguish the controller methods when the url is requested. The two separate request urls are configured using two controller methods. This will solve the exception.

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {

	@RequestMapping("/welcome")
	public ModelAndView welcomepage() {
		return new ModelAndView("welcome");
	}

	@RequestMapping("/hello")
	public ModelAndView helloworld() {
		return new ModelAndView("welcome");
	}
}

Solution 2

The controller methods can be configured using the same request url using different request mapping methods. If two methods are configured with the same url, one using the GET method and the other using the POST method, the rest controller will distinguish by method.

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {

	@RequestMapping(value="/welcome", method = RequestMethod.GET)
	public ModelAndView welcomepage() {
		return new ModelAndView("welcome");
	}

	@RequestMapping(value="/welcome", method = RequestMethod.POST)
	public ModelAndView helloworld() {
		return new ModelAndView("welcome");
	}
}

Solution 3

If the spring boot application is configured with two or more rest controller classes, there may be possible to create the same url with two different methods in multiple rest controller classes. All the rest controller classes must be checked for the url configured in multiple locations. The exception will be resolved by configuring a unique url across all rest controller classes.

WelcomeController.java

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WelcomeController {

	@RequestMapping("/welcome")
	public ModelAndView welcomepage() {
		return new ModelAndView("welcome");
	}
}

HelloController.java

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
	@RequestMapping("/welcome")
	public ModelAndView helloworld() {
		return new ModelAndView("welcome");
	}
}

To fix the error in the example above, change the url for any of the rest of the controller methods.

I have an application with spring that use a JpaConfiguration class to deal with my database, and a WebAppMvcConfigurer class to deal with the front via json message. Both have an @Configuration and are in the same package. I have an App class in a root package with @Configuration and @ComponentScan with my main method.

When I launch App class I get this error :

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
    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.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)
    at com.bnpp.creditauto.App.main(App.java:22)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
    ... 14 more
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:73)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:533)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 15 more

What «works» so far is delete one of the two @Configuration in either JpaConfiguration or WebAppMvcConfigurer. If i delete the @Configuration WebApp one i can interact with my database no problem, but cant access anything from my angular application.
If I delete the @Configuration in JpaConf the front part of the application works and I can access the json my Java application sends with my angular application no problem, but cant do anything with my database.

Somewhere I read to change @Configuation to @WebAppConfiguration in WebAppMvcConfigurer, it does the same as removing the @Configuration, JpaConfiguration works fine and front part doesnt work.

I checked dependencies and tried the last version without success.
I tried to change in App : @ComponentScan(basePackages = { "org.example.springproject" }, excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
without success too, it is the same as deleting both @Configuration in Jpa and webapp

My app class :

package com.bnpp.creditauto;

@Configuration
@ComponentScan//("com.bnpp.creditauto")
public class App {

    public static void main(String[] args) {
        ...
}

JpaConfiguration class :

package com.bnpp.creditauto.config;

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class JpaConfiguration {
  ...
}

WebAppMvcConfigurer class :

package com.bnpp.creditauto.config;

@Configuration
@EnableWebMvc
public class WebAppMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

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

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

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

  • 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 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии