I have a SpringBoot application (version 1.5.22.RELEASE), and it's using a MariaDB database as datasource to get some data to populate a cache at startup. The data comes from a JPA Repositoy using a collection of a Entity. All the datasource parameters are in the application.properties
file.
At this moment, I have to switch the cache datasource to a REST service instead the database. If I have a new property with the value in true
, I must use the REST service because the DB will be off; otherwise (with the new property in false
), I must use the database, because the REST service will be unavailable.
When I try to test my application with the property in true
and the database unavailable, the application throws the following error, and the application doesn't start:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.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:1630) ~[spring-beans-4.3.25.RELEASE.jar:4.3.25.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.25.RELEASE.jar:4.3.25.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) ~[spring-beans-4.3.25.RELEASE.jar:4.3.25.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) ~[spring-beans-4.3.25.RELEASE.jar:4.3.25.RELEASE]
Is there a way to avoid this error when the database isn´t available and continue with the application startup?
Thanks in advance. I appreciate your help and feedback.
Yes, you can disable the database autoconfiguration by using code below:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(PayPalApplication.class, args);
}
}
And then in the startup, you can connect to the database manually . Detect the availability of the database, fetch cache data or get a connection error, then switch to the backup service.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.