Error creating bean with name перевод

Как решить org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘userController’? Помогите решить такую ошибку, уже не знаю что делать, Любая помощь ценится. В стек трейсе говорит проблема с полем userService в контроллере но я не пойму что мне нужно сделать с ним! Конфигурационные файлы стпринг app-config Вопрос задан более трёх лет назад 12336 просмотров Простой […]

Содержание

  1. Как решить org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘userController’?
  2. Spring Boot Error — Error creating a bean with name ‘dataSource’ defined in class path resource DataSourceAutoConfiguration
  3. 1. Spring Boot Error due to Starter Dependency
  4. 2. Due to Missing Dependency
  5. 3. Due to Missing Configuration in Application.properties
  6. 4. Exclude DataSourceAutoConfiguration
  7. 2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]
  8. 1) No default constructor on Spring Bean
  9. 2) Spring Bean dependent on third party library

Как решить org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘userController’?

Помогите решить такую ошибку, уже не знаю что делать, Любая помощь ценится.
В стек трейсе говорит проблема с полем userService в контроллере но я не пойму что мне нужно сделать с ним!
Конфигурационные файлы стпринг
app-config

  • Вопрос задан более трёх лет назад
  • 12336 просмотров

Простой 3 комментария

No qualifying bean of type ‘com.service.UserService’ available: expected at least 1 bean which qualifies as autowire candidate

P_Alexander, Дававайте сделаем в контроллере
@Autowired
@Qualifier(«myUserService»)
private UserService userService;

И в самом сервисе
@Service
@Qualifier(«myUserService»)
@Transactional
public class UserServiceImpl implements UserService<

P_Alexander, я так понял, суть в том, что вы хотите заавтовайрить интерфейс. И, несмотря на то, что в проекте у вас всего один имплементатор, спрингу не очевидно, что нужно автовайрить именно UserServiceImpl

Источник

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.

Источник

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

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

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

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

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

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

1) No default constructor on Spring Bean

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

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

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

The most important line in this stack trace is

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

which is often overlooked by Java programmers.

2) Spring Bean dependent on third party library

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

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

Источник

Добрый день, столкнулся с проблемой — Error creating bean with name ‘entityManagerFactory’. Не могу понять, как ее разрешить.
Скажите, какую еще информацию необходимо предоставить.
Спасибо

Tomcat localhost log:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in web.config.HibernateConfig: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
		at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
		at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
		at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
		at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
		at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)
		at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
		at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551)
		at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:401)
		at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:292)
		at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
		at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4676)
		at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5139)
		at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
		at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717)
		at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
		at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
		at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1727)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:288)
		at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
		at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
		at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:456)
		at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:405)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:288)
		at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
		at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
		at com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
		at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
		at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
		at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
		at java.security.AccessController.doPrivileged(Native Method)
		at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1408)
		at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
		at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
		at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
		at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
		at java.lang.reflect.Method.invoke(Method.java:498)
		at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
		at sun.rmi.transport.Transport$1.run(Transport.java:200)
		at sun.rmi.transport.Transport$1.run(Transport.java:197)
		at java.security.AccessController.doPrivileged(Native Method)
		at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
		at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
		at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
		at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
		at java.security.AccessController.doPrivileged(Native Method)
		at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
		at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
		at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
		at java.lang.Thread.run(Thread.java:748)
	Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
		at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
		at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
		at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
		at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
		at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
		at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
		at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
		at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176)
		at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
		at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224)
		at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255)
		at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
		at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
		at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
		at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378)
		at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853)
		at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790)
		... 59 more

Страницы 1

Чтобы отправить ответ, нужно авторизоваться или зарегистрироваться

#1 2022-01-12 19:21:01

  • ClawX
  • Посетитель
  • Неактивен

Не запускается УТМ. (Error creating bean with name ‘ipAccessHolder’)

Здравствуйте!

Ограничили доступ к УТМ по списку IP.
После перезагрузки УТМ не запускается.
В логах ошибки:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘whiteListIPFilter’: Unsatisfied dependency expressed through field ‘ipAccessHolder’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘ipAccessHolder’: Invocation of init method failed; nested exception is java.lang.NullPointerException

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘ipAccessHolder’: Invocation of init method failed; nested exception is java.lang.NullPointerException

#2 Ответ от ClawX 2022-01-12 21:19:19

  • ClawX
  • Посетитель
  • Неактивен

Re: Не запускается УТМ. (Error creating bean with name ‘ipAccessHolder’)

Если отредактировать конфигурационный файл C:UTMtransporterconftransport.properties

И в параметре «web.server.attempt.ip =» убрать все IP адреса, то УТМ запускается и работает.

#3 Ответ от Ксения Шаврова 2022-01-12 21:58:17

  • Ксения Шаврова
  • Администратор
  • Неактивен

Re: Не запускается УТМ. (Error creating bean with name ‘ipAccessHolder’)

ClawX, здравствуйте.
С этим вопросом наша компания вам помочь не сможет. Мы стараемся помогать по вопросам ЕГАИС, связанным с Рутокенами и ключами на них

Сообщений 3

Страницы 1

Чтобы отправить ответ, нужно авторизоваться или зарегистрироваться

Работаю в Eclipse и изучаю Spring по официальным гайдам (конкретнее — вот этот, без какой либо отсебятины на текущий момент) и получаю ошибку

Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Полный лог из консоли после появления ошибки:

Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at hello.Application.main(Application.java:10) [classes/:na]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1821) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1758) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	... 16 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
	at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
	... 33 common frames omitted

Насколько я понимаю, после изучения похожих вопросов, проблема тут в зависимостях. Проверил дерево зависимостей и понял, что я не понимаю, как его прочесть и каких зависимостей мне не хватает.
1. Дерево зависимостей:

[INFO] org.springframework:gs-mysql-data:jar:0.1.0
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.1.3.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:2.1.3.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:2.1.3.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.1.3.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.1.3.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  |  |  |  - ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.11.2:compile
[INFO] |  |  |  |  - org.apache.logging.log4j:log4j-api:jar:2.11.2:compile
[INFO] |  |  |  - org.slf4j:jul-to-slf4j:jar:1.7.25:compile
[INFO] |  |  +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  |  - org.yaml:snakeyaml:jar:1.23:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-json:jar:2.1.3.RELEASE:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.8:compile
[INFO] |  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] |  |  |  - com.fasterxml.jackson.core:jackson-core:jar:2.9.8:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.8:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.8:compile
[INFO] |  |  - com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.9.8:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.1.3.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.16:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.16:compile
[INFO] |  |  - org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.16:compile
[INFO] |  +- org.hibernate.validator:hibernate-validator:jar:6.0.14.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:2.0.1.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.2.Final:compile
[INFO] |  |  - com.fasterxml:classmate:jar:1.4.0:compile
[INFO] |  +- org.springframework:spring-web:jar:5.1.5.RELEASE:compile
[INFO] |  |  - org.springframework:spring-beans:jar:5.1.5.RELEASE:compile
[INFO] |  - org.springframework:spring-webmvc:jar:5.1.5.RELEASE:compile
[INFO] |     +- org.springframework:spring-aop:jar:5.1.5.RELEASE:compile
[INFO] |     +- org.springframework:spring-context:jar:5.1.5.RELEASE:compile
[INFO] |     - org.springframework:spring-expression:jar:5.1.5.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:2.1.3.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-aop:jar:2.1.3.RELEASE:compile
[INFO] |  |  - org.aspectj:aspectjweaver:jar:1.9.2:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:2.1.3.RELEASE:compile
[INFO] |  |  +- com.zaxxer:HikariCP:jar:3.2.0:compile
[INFO] |  |  - org.springframework:spring-jdbc:jar:5.1.5.RELEASE:compile
[INFO] |  +- javax.transaction:javax.transaction-api:jar:1.3:compile
[INFO] |  +- javax.xml.bind:jaxb-api:jar:2.3.1:compile
[INFO] |  |  - javax.activation:javax.activation-api:jar:1.2.0:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:5.3.7.Final:compile
[INFO] |  |  +- javax.persistence:javax.persistence-api:jar:2.2:compile
[INFO] |  |  +- org.javassist:javassist:jar:3.23.1-GA:compile
[INFO] |  |  +- net.bytebuddy:byte-buddy:jar:1.9.10:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  |  +- org.jboss:jandex:jar:2.0.5.Final:compile
[INFO] |  |  +- org.dom4j:dom4j:jar:2.1.1:compile
[INFO] |  |  - org.hibernate.common:hibernate-commons-annotations:jar:5.0.4.Final:compile
[INFO] |  +- org.springframework.data:spring-data-jpa:jar:2.1.5.RELEASE:compile
[INFO] |  |  +- org.springframework.data:spring-data-commons:jar:2.1.5.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-orm:jar:5.1.5.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-tx:jar:5.1.5.RELEASE:compile
[INFO] |  |  - org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] |  - org.springframework:spring-aspects:jar:5.1.5.RELEASE:compile
[INFO] +- mysql:mysql-connector-java:jar:8.0.15:compile
[INFO] - org.springframework.boot:spring-boot-starter-test:jar:2.1.3.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test:jar:2.1.3.RELEASE:test
[INFO]    +- org.springframework.boot:spring-boot-test-autoconfigure:jar:2.1.3.RELEASE:test
[INFO]    +- com.jayway.jsonpath:json-path:jar:2.4.0:test
[INFO]    |  - net.minidev:json-smart:jar:2.3:test
[INFO]    |     - net.minidev:accessors-smart:jar:1.2:test
[INFO]    |        - org.ow2.asm:asm:jar:5.0.4:test
[INFO]    +- junit:junit:jar:4.12:test
[INFO]    +- org.assertj:assertj-core:jar:3.11.1:test
[INFO]    +- org.mockito:mockito-core:jar:2.23.4:test
[INFO]    |  +- net.bytebuddy:byte-buddy-agent:jar:1.9.10:test
[INFO]    |  - org.objenesis:objenesis:jar:2.6:test
[INFO]    +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO]    +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO]    +- org.skyscreamer:jsonassert:jar:1.5.0:test
[INFO]    |  - com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test
[INFO]    +- org.springframework:spring-core:jar:5.1.5.RELEASE:compile
[INFO]    |  - org.springframework:spring-jcl:jar:5.1.5.RELEASE:compile
[INFO]    +- org.springframework:spring-test:jar:5.1.5.RELEASE:test
[INFO]    - org.xmlunit:xmlunit-core:jar:2.6.2:test
  1. 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>

	<groupId>org.springframework</groupId>
	<artifactId>gs-mysql-data</artifactId>
	<version>0.1.0</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3.RELEASE</version>
	</parent>

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

	
		<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->

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

		<!-- Use MySQL Connector-J -->

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

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

</project>
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
  1. Класс Application (единственный класс, на который в консоли есть ссылки, ругается на 10 строчку)
package hello;

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

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. Класс User
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}


}
  1. Класс реопзитория
package hello;

import org.springframework.data.repository.CrudRepository;

import hello.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Integer> {

}
  1. Класс контроллера
package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import hello.User;
import hello.UserRepository;

@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
	@Autowired // This means to get the bean called userRepository
	           // Which is auto-generated by Spring, we will use it to handle the data
	private UserRepository userRepository;

	@GetMapping(path="/add") // Map ONLY GET Requests
	public @ResponseBody String addNewUser (@RequestParam String name
			, @RequestParam String email) {
		// @ResponseBody means the returned String is the response, not a view name
		// @RequestParam means it is a parameter from the GET or POST request

		User n = new User();
		n.setName(name);
		n.setEmail(email);
		userRepository.save(n);
		return "Saved";
	}

	@GetMapping(path="/all")
	public @ResponseBody Iterable<User> getAllUsers() {
		// This returns a JSON or XML with the users
		return userRepository.findAll();
	}
}

Собственно вопрос — как правильно читать это дерево? Как мне узнать, какие параметры необходимо вписать в описание новой заивисимости?

28.07.2022

518 Просмотры

Error creating bean with name ‘liquibase’ defined in class path resource … /config/DatabaseConfiguration.class

У меня есть эта раздражающая ошибка при запуске Embedded Tomcat в моем проекте jHipster. Я потратил много времени, пытаясь решить эту проблему, но не могу понять, почему это происходит. Это начало происходить после обновления проекта из основного репозитория, но я также внедрил пользовательский репозиторий.

Известно, что Liquibase записывает все журналы изменений в таблицу databasechangelog в вашей базе данных:

Корнем всех изменений Liquibase является файл databaseChangeLog.

Когда у меня возникла подобная ошибка, я решил ее вручную, изменив значение контрольной суммы в таблице databasechangelog в моей базе данных. Вы можете решить эту проблему, выполнив следующий SQL-запрос в вашей базе данных:

UPDATE `databasechangelog` SET `MD5SUM`=`7:bde7b076d47aefe8278d126cde26b172` WHERE `ID`=`00000000000001`;


Я запускаю свое приложение в соответствии с инструкциями блога (https://spring.io/blog/2020/04/09/spring-graal-native-0-6-0-released), однако, когда я использую зависимость spring/graal, предоставленную командой spring, мне нужно как минимум “> 16gb” памяти для компиляции, иначе выдает ошибку “out of memory”.

Ошибка, которую я получаю в данный момент относительно liquibase

Загрузка…

Полная ошибка

Error creating bean with name 'itemController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.e3mall.service.ItemService cn.e3mall.controller.ItemController.itemService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cn.e3mall.service.ItemService] 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)}
----------------------------------------------------------------
Could not autowire field: private cn.e3mall.service.ItemService cn.e3mall.controller.ItemController.itemService

При ближайшем рассмотрении выясняется, что вы забыли добавить @Service в ItemServiceImpl

Когда контрольный уровень вызывает бизнес-уровень, бизнес-уровень должен быть аннотирован

Только тогда уровень обслуживания может быть подключен к уровню управления

Если он не был разрешен после перезапуска, вероятно, что код не был обновлен и синхронизирован во времени;

F5, проект решен

I am trying to write test for my spring boot application. For the independent controller test, i have used @WebMvcTest but ran into some issues. Here is the basic structure of the code.

UserController has UserService class autowired.

LibraryController has LibraryService class autowired.

Here is the code for the UserControllerTest ::

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
   @Autowired
   private MockMvc mockMvc;
   
   @MockBean
    private UserService userServiceMock;

   @Test
   public void someTest(){}

}

It is giving the error while running the code in UserControllerTest:

Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name ‘libraryController’: Unsatisfied
dependency expressed through field ‘libraryService’; nested
exception is org.springframework.beans.factory

As per my understanding, since we have specified UserController inside @WebMvcTest annotation, we need to mock only the dependency required by that controller. But it is asking for the libraryService which have no links with the usercontroller.

And yeah if we include the library service as MockBean inside the test, then it works fine. But if this is the case we have to mock each and every autowired beans as the program scales.

Any explanation is appreciated. Thanks in advance.

I am trying to write test for my spring boot application. For the independent controller test, i have used @WebMvcTest but ran into some issues. Here is the basic structure of the code.

UserController has UserService class autowired.

LibraryController has LibraryService class autowired.

Here is the code for the UserControllerTest ::

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
   @Autowired
   private MockMvc mockMvc;
   
   @MockBean
    private UserService userServiceMock;

   @Test
   public void someTest(){}

}

It is giving the error while running the code in UserControllerTest:

Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name ‘libraryController’: Unsatisfied
dependency expressed through field ‘libraryService’; nested
exception is org.springframework.beans.factory

As per my understanding, since we have specified UserController inside @WebMvcTest annotation, we need to mock only the dependency required by that controller. But it is asking for the libraryService which have no links with the usercontroller.

And yeah if we include the library service as MockBean inside the test, then it works fine. But if this is the case we have to mock each and every autowired beans as the program scales.

Any explanation is appreciated. Thanks in advance.

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



Я пытаюсь запустить свои тесты проекта в контейнере докера. Все тесты прекрасно работают при локальном запуске. Ошибки начали появляться, когда я пытался переместить тестирование в контейнер докера. Вот сообщение об ошибке:

java.lang.IllegalStateException: Failed to load ApplicationContext
[...]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException: 
Migration V1__initial_user.sql failed
-------------------------------------
SQL State  : 42601
Error Code : 0
Message    : ERROR: syntax error at or near "GENERATED"
  Position: 45
Location   : db/migration/V1__initial_user.sql (/Users/villemossip/Desktop/GRP/GRP-SAS/application/build/resources/main/db/migration/V1__initial_user.sql)
Line       : 36
Statement  : CREATE TABLE revinfo
(
    rev      INTEGER GENERATED BY DEFAULT AS IDENTITY ( START WITH 1 ),
    revtstmp BIGINT,
    PRIMARY KEY (rev)
)

Из журнала видно, что образ контейнера был создан, но он не может перенести схему sql:

[...]
2019-10-10 10:36:18.768  INFO 49547 --- [           main] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 5.2.4 by Boxfuse
2019-10-10 10:36:18.777  INFO 49547 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-10-10 10:36:18.795  INFO 49547 --- [           main] 🐳 [postgres:9.6.12]                     : Creating container for image: postgres:9.6.12
2019-10-10 10:36:19.001  INFO 49547 --- [           main] 🐳 [postgres:9.6.12]                     : Starting container with ID: a32dd0850baf34770cce9bdc81918cd4db40502188b85dfaa90f74e2900f9fa7
2019-10-10 10:36:19.547  INFO 49547 --- [           main] 🐳 [postgres:9.6.12]                     : Container postgres:9.6.12 is starting: a32dd0850baf34770cce9bdc81918cd4db40502188b85dfaa90f74e2900f9fa7
2019-10-10 10:36:23.342  INFO 49547 --- [           main] 🐳 [postgres:9.6.12]                     : Container postgres:9.6.12 started
2019-10-10 10:36:23.426  INFO 49547 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-10-10 10:36:23.431  INFO 49547 --- [           main] o.f.c.internal.database.DatabaseFactory  : Database: jdbc:postgresql://localhost:32834/test (PostgreSQL 9.6)
2019-10-10 10:36:23.488  INFO 49547 --- [           main] o.f.core.internal.command.DbValidate     : Successfully validated 6 migrations (execution time 00:00.024s)
2019-10-10 10:36:23.501  INFO 49547 --- [           main] o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table: "public"."flyway_schema_history"
2019-10-10 10:36:23.519  INFO 49547 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema "public": << Empty Schema >>
2019-10-10 10:36:23.520  INFO 49547 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema "public" to version 1 - initial user
2019-10-10 10:36:23.542 ERROR 49547 --- [           main] o.f.core.internal.command.DbMigrate      : Migration of schema "public" to version 1 - initial user failed! Changes successfully rolled back.
2019-10-10 10:36:23.546  WARN 49547 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException: 
Migration V1__initial_user.sql failed
-------------------------------------
[...]

Вот часть сценария sql (app / src / main / resources / db /igration):

[...]
constraint user_aud_pkey primary key (id, rev)
);

CREATE TABLE revinfo
(
    rev      INTEGER GENERATED BY DEFAULT AS IDENTITY ( START WITH 1 ),
    revtstmp BIGINT,
    PRIMARY KEY (rev)
);

CREATE SEQUENCE hibernate_sequence INCREMENT 1 MINVALUE 1
    MAXVALUE 9223372036854775807
    START 1
    CACHE 1;

Вот «application.properties» (app / test / java / resources):

spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver
spring.datasource.url=jdbc:tc:postgresql://localhost:5433/test
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=validate
spring.jackson.default-property-inclusion=NON_NULL

spring.flyway.baselineOnMigrate=true
spring.flyway.check-location=true
spring.flyway.locations=classpath:db/migration
spring.flyway.schemas=public
spring.flyway.enabled=true

Также в том же каталоге у меня есть файл container-license-accept.txt.

Внутри «build.gradle» я добавил следующие строки (app / build.gradle):

dependencies {
    [...]
    testImplementation "org.testcontainers:junit-jupiter:1.11.3"
    testImplementation "org.testcontainers:postgresql:1.11.3"

}

Внутри файла BaseInitTest у меня есть следующие строки (app / test / java / com):

@Testcontainers
@SpringBootTest
public class BaseIntTest {

    @Container
    private static final PostgreSQLContainer<?> container = new PostgreSQLContainer<>();

    [...]

Я не понимаю, как могут сначала проходить одни и те же тесты, но не удается, когда я перемещаю их в докер-контейнер?

2 ответа

Лучший ответ

Спасибо, @M. Deinum и Марк Брамник!

Я узнал, что проблема с версией Postgres. По какой-то причине по умолчанию образ докера создается со старой версией 9.6.12, но SQL-скрипт GENERATED BY DEFAULT был добавлен в Postgres с версией 10.

Решение 1 (обновите сценарий sql до более старой версии):

CREATE TABLE revinfo
(
    rev      INTEGER PRIMARY KEY NOT NULL,
    revtstmp BIGINT
);

Решение 2: Изменена версия образа докера на 11.2 путем создания файла CustomPostgreSQLContainer в проекте.

import org.testcontainers.containers.PostgreSQLContainer;

public class CustomPostgreSQLContainer extends PostgreSQLContainer<CustomPostgreSQLContainer> {
    private static final String IMAGE_VERSION = "postgres:11.2";
    private static CustomPostgreSQLContainer container;
    CustomPostgreSQLContainer() {
        super(IMAGE_VERSION);
    }
    public static CustomPostgreSQLContainer getInstance() {
        if (container == null) {
            container = new CustomPostgreSQLContainer();
        }
        return container;
    }
    @Override
    public void start() {
        super.start();
        System.setProperty("spring.datasource.url", container.getJdbcUrl());
        System.setProperty("spring.datasource.username", container.getUsername());
        System.setProperty("spring.datasource.password", container.getPassword());
    }
    @Override
    public void stop() {
        //do nothing, JVM handles shut down
    }
}

И обновление файла BaseIntTest:

@Testcontainers
@SpringBootTest
public class BaseIntTest {

    @Container
    private static final PostgreSQLContainer<?> container = CustomPostgreSQLContainer.getInstance();

И последнее удаление двух строк из тестового файла application.properties:

spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver
spring.datasource.url=jdbc:tc:postgresql://localhost:5433/test


1

Tambet Tamm
10 Окт 2019 в 11:55

Похоже, что тестовый контейнер с базой данных успешно запущен, так что нет проблем, вы получаете пустую базу данных.

Затем вы пытаетесь запустить пролетный путь, и это не удается. Весенняя загрузка Flyway работает во время инициализации контекста приложения Spring, поэтому фактическая миграция выполняется во время инициализации контекста приложения, поэтому сбой миграции выглядит как сбой пружины.

Причина, однако, записывается: файл миграции содержит недопустимое содержимое:

Migration V1__initial_user.sql failed
-------------------------------------
SQL State  : 42601
Error Code : 0
Message    : ERROR: syntax error at or near "GENERATED"
 Position: 45
Location   : db/migration/V1__initial_user.sql (/Users/villemossip/Desktop/GRP/GRP- 
SAS/application/build/resources/main/db/migration/V1__initial_user.sql)
Line       : 36
Statement  : CREATE TABLE revinfo
(
   rev      INTEGER GENERATED BY DEFAULT AS IDENTITY ( START WITH 1 ),
   revtstmp BIGINT,
   PRIMARY KEY (rev)
)

Это GENERATED BY не поддерживается.

Зачем? Возможно, ваш образ докера включает версию RDBMS, которая не поддерживает этот синтаксис. Так что он отличается от БД, которую вы используете в локальной среде без докера.

В любом случае речь идет не о докере, пружине или пролетном пути, а о БД и коде миграции.

С точки зрения разрешения, я предлагаю запустить образ докера БД напрямую (без java, testcontainers и flyway). Когда он запускается, просто запустите эту миграцию «вручную» в pgadmin или что-то в этом роде. Вы ожидаете увидеть ту же ошибку.


1

Mark Bramnik
10 Окт 2019 в 08:47

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

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

  • Error creating bean with name viewresolver
  • Error creating bean with name tomcatservletwebserverfactory
  • Error creating bean with name suncryptographer
  • Error creating bean with name router function mapping
  • Error creating bean with name resource handler mapping

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

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