Migrating from Migrate to Spring MVC 4 + Hibernate5 - java

I'm migrating an application from Jersey 1.18, Spring 3, Hibernate 3.6, Maven to a completely new architecture: Spring 4.3 (via Spring Boot), Hibernate 5 and Gradle.
During the "porting" of the Spring application.xml to a Code-Base configuration, I'm facing the following exception:
Error creating bean with name 'jpaContext': Unsatisfied dependency ... No qualifying bean found for dependency [java.util.Set]
Here the long stacktrace
2017-03-13 19:44:42.814 WARN 40010 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jpaContext': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [java.util.Set<javax.persistence.EntityManager>]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2017-03-13 19:44:42.816 INFO 40010 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-03-13 19:44:42.825 INFO 40010 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2017-03-13 19:44:42.860 INFO 40010 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-03-13 19:44:42.995 ERROR 40010 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in org.springframework.data.jpa.repository.support.DefaultJpaContext required a bean of type 'java.util.Set' that could not be found.
Action:
Consider defining a bean of type 'java.util.Set' in your configuration.
The fact is that I didn't define the DefaultJpaContext in my code:
#Configuration
#EnableTransactionManagement
#EnableAspectJAutoProxy(proxyTargetClass = true)
public class DatabaseConfig {
#Autowired private Environment env;
#Autowired private DataSource dataSource;
#Autowired private SessionFactory sessionFactory;
private static final String DB_DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
private static final String HIBERNATE_DIALECT = "org.hibernate.dialect.MySQL5Dialect";
private static final String HIBERNATE_VALIDATION = "validate";
private static final String SHOW_SQL = "false";
private static final String ENTITY_PACKAGE = MainEntity.class.getPackage().getName();
final Logger log = LoggerFactory.getLogger(DatabaseConfig.class);
#Bean
public DataSource dataSource() {
final String driverName = env.getProperty("db.driver", DB_DRIVER_CLASS_NAME);
final String url = env.getProperty("db.url");
final String username = env.getProperty("db.username");
final String password = env.getProperty("db.password");
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
if (log.isInfoEnabled()) {
log.info("Database Configuration:");
log.info("Setting driverName to {}", driverName);
log.info("Setting url to {}", url);
log.info("Setting username to {}", username);
if (StringUtils.isEmpty(password)) log.warn("Password not specified");
else log.info("Setting password");
}
dataSource.setDriverClassName(driverName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setPackagesToScan(new String[] {ENTITY_PACKAGE});
// Hibernate properties
Properties additionalProperties = new Properties();
additionalProperties.put("hibernate.dialect" , env.getProperty("db.dialect" , HIBERNATE_DIALECT));
additionalProperties.put("hibernate.hbm2ddl.auto", env.getProperty("db.validation", HIBERNATE_VALIDATION));
additionalProperties.put("hibernate.show_sql" , env.getProperty("db.sql.show" , SHOW_SQL));
sessionFactory.setHibernateProperties(additionalProperties);
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager(){
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
}
Update
Here it is a piece of gradle build:
compile('org.springframework.boot:spring-boot-starter-data-jpa')
// ...
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.hibernate' , name: 'hibernate-core' , version: '5.2.8.Final'
// ...
What I'm missing?
Thanks, Davide.

Based on the spring boot error message, it fails to build the DefaultJpaContext bean whose constructor requires Set<javax.persistence.EntityManager> entityManagers.
Looks like you have Spring-Data dependency in your pom.xml(or build.gradle) which requires the jpa EntityManagerFactory while you have Hibernate(LocalSessionFactoryBean) stuff. Do you have to have DefaultJpaContext bean?

Related

Quartz Spring Boot There is no DataSource named 'dataSource'

I have the following quartz.properties:
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.dataSource=dataSource
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
org.quartz.jobStore.tablePrefix=qrtz_
org.quartz.threadPool.threadCount=1
org.quartz.scheduler.skipUpdateCheck=true
org.quartz.plugin.triggerHistory.class=org.quartz.plugins.history.LoggingTriggerHistoryPlugin
Also, I added QuartzConfiguration:
#Configuration
#EnableScheduling
public class QuartzConfiguration {
public static final String CONTEXT_KEY = "applicationContext";
#Autowired
private DataSource dataSource;
#Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
scheduler.setApplicationContextSchedulerContextKey("applicationContext");
scheduler.setConfigLocation(new ClassPathResource("quartz.properties"));
scheduler.setDataSource(dataSource);
scheduler.setWaitForJobsToCompleteOnShutdown(true);
return scheduler;
}
}
In the application.properties I have defined:
#PostgreSQL
spring.datasource.url=${postgresql.datasource.url}
spring.datasource.username=${postgresql.datasource.username}
spring.datasource.password=${postgresql.datasource.password}
Right now, during start up the application fails with the following exception:
Caused by: org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'dataSource': java.sql.SQLException: There is no DataSource named 'dataSource' [See nested exception: java.sql.SQLException: There is no DataSource named 'dataSource']
at org.quartz.impl.jdbcjobstore.JobStoreSupport.getConnection(JobStoreSupport.java:783)
at org.quartz.impl.jdbcjobstore.JobStoreTX.getNonManagedTXConnection(JobStoreTX.java:71)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.executeInNonManagedTXLock(JobStoreSupport.java:3861)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.recoverJobs(JobStoreSupport.java:839)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.schedulerStarted(JobStoreSupport.java:695)
... 45 more
Caused by: java.sql.SQLException: There is no DataSource named 'dataSource'
at org.quartz.utils.DBConnectionManager.getConnection(DBConnectionManager.java:104)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.getConnection(JobStoreSupport.java:780)
... 49 more
What am I doing wrong and how to provide a correct DataSource to the org.quartz.jobStore.dataSource ?
Two options:
create a configuration bean that specifically creates you DataSource.
#Bean
public DataSource getDataSource()
{
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:file:C:/temp/test");
dataSourceBuilder.username("sa");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
You can alternatively use JNDI, use the spring.datasource.jndi-name
see also

Cannot create inner beanof type org.springframework.orm.jpa.SharedEntityManagerCreator error while Spring boot application deployed on aws

I have deployed multitenant Spring boot application on AWS EC2. the code just works fine in the local system, but application is failing with below error after docker run in aws ec2.
] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderReportListener' defined in URL [jar:file:/app-service.jar!/BOOT-INF/classes!/com/aic/autofluence/appservice/scheduler/kafkaReportListener/OrderReportListener.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'reportFactoryImplData' defined in URL [jar:file:/app-service.jar!/BOOT-INF/classes!/com/aic/autofluence/appservice/scheduler/service/Impl/ReportFactoryImplData.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderReportRepository' defined in com.aic.autofluence.appservice.scheduler.repository.OrderReportRepository defined in #EnableJpaRepositories declared on TenantDatabaseConfig: Cannot create inner bean '(inner bean)#4293e066' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#4293e066': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2021-05-10 18:58:57.081 INFO 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'masterdb-persistence-unit'
2021-05-10 18:58:57.082 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : masterdb-connection-pool - Shutdown initiated...
2021-05-10 18:58:57.099 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : masterdb-connection-pool - Shutdown completed.
2021-05-10 18:58:57.103 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-05-10 18:58:57.124 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-05-10 18:58:57.147 ERROR 1 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.aic.autofluence.appservice.scheduler.service.Impl.ReportFactoryImplData required a bean named 'entityManagerFactory' that could not be found.
Sample code I have as below:
tenantConfig: The EntityManagerFactory bean itself is not recognised. it is working good in local system, failing same in vm
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = { "x.x.x.x.scheduler.repository", "x.x.x.x.scheduler.model" })
#EnableJpaRepositories(basePackages = {"x.x.x.x..scheduler.repository", "x.x.x.x..scheduler.service"},
entityManagerFactoryRef = "tenantEntityManagerFactory",
transactionManagerRef = "tenantTransactionManager")
public class TenantDatabaseConfig {
#Bean(name = "tenantJpaVendorAdapter")
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter ();
}
#Bean(name = "tenantTransactionManager")
public JpaTransactionManager transactionManager(#Qualifier("tenantEntityManagerFactory") EntityManagerFactory tenantEntityManager) {
JpaTransactionManager transactionManager = new JpaTransactionManager ();
transactionManager.setEntityManagerFactory(tenantEntityManager);
return transactionManager;
}
#Bean(name = "datasourceBasedMultitenantConnectionProvider")
#ConditionalOnBean(name = "masterEntityManagerFactory")
public MultiTenantConnectionProvider multiTenantConnectionProvider() {
return new DataSourceBasedMultiTenantConnectionProviderImpl();
}
#Bean(name = "currentTenantIdentifierResolver")
public CurrentTenantIdentifierResolver currentTenantIdentifierResolver() {
return new CurrentTenantIdentifierResolverImpl();
}
#Bean(name = "tenantEntityManagerFactory")
#ConditionalOnBean(name = "datasourceBasedMultitenantConnectionProvider")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
#Qualifier("datasourceBasedMultitenantConnectionProvider")
MultiTenantConnectionProvider connectionProvider,
#Qualifier("currentTenantIdentifierResolver")
CurrentTenantIdentifierResolver tenantResolver) {
LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean ();
//All tenant related entities, repositories and service classes must be scanned
emfBean.setPackagesToScan("com.aic.autofluence.appservice");
emfBean.setJpaVendorAdapter(jpaVendorAdapter());
emfBean.setPersistenceUnitName("tenantdb-persistence-unit");
Map<String, Object> properties = new HashMap<>();
properties.put( Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
properties.put( Environment.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
properties.put( Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
properties.put( Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
properties.put( Environment.SHOW_SQL, true);
properties.put( Environment.FORMAT_SQL, true);
properties.put( Environment.HBM2DDL_AUTO, "none");
emfBean.setJpaPropertyMap(properties);
return emfBean;
}
}
**MasterConfig: It is configured properly working fine**
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"x.x.x.x.mastertenant.model",
"x.x.x.x.mastertenant.repository"
},
entityManagerFactoryRef = "masterEntityManagerFactory",
transactionManagerRef = "masterTransactionManager")
public class MasterDatabaseConfig {
private static final Logger LOG = LoggerFactory.getLogger(MasterDatabaseConfig.class);
#Autowired
private MasterDatabaseConfigProperties masterDbProperties;
#Bean(name = "masterDataSource")
public DataSource masterDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource ();
hikariDataSource.setUsername(masterDbProperties.getUsername());
hikariDataSource.setPassword(masterDbProperties.getPassword());
hikariDataSource.setJdbcUrl(masterDbProperties.getUrl());
hikariDataSource.setDriverClassName(masterDbProperties.getDriverClassName());
hikariDataSource.setPoolName(masterDbProperties.getPoolName());
// HikariCP settings
hikariDataSource.setMaximumPoolSize(masterDbProperties.getMaxPoolSize());
hikariDataSource.setMinimumIdle(masterDbProperties.getMinIdle());
hikariDataSource.setConnectionTimeout(masterDbProperties.getConnectionTimeout());
hikariDataSource.setIdleTimeout(masterDbProperties.getIdleTimeout());
LOG.info("Setup of masterDataSource succeeded.");
return hikariDataSource;
}
#Primary
#Bean(name = "masterEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean masterEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean ();
em.setDataSource(masterDataSource());
em.setPackagesToScan(new String[]{x,x,x,x...});
em.setPersistenceUnitName("masterdb-persistence-unit");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter ();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(hibernateProperties());
LOG.info("Setup of masterEntityManagerFactory succeeded.");
return em;
}
#Bean(name = "masterTransactionManager")
public JpaTransactionManager masterTransactionManager(#Qualifier("masterEntityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager ();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor ();
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put(org.hibernate.cfg.Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
properties.put(org.hibernate.cfg.Environment.SHOW_SQL, true);
properties.put(org.hibernate.cfg.Environment.FORMAT_SQL, true);
properties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO, "none");
return properties;
}
Any Idea what might be the issue?
Thanks
I have resolved this issue by removing the #ConditionalOnBean annotation. Thanks for the people who responded.
the code just works fine in the local system, but application is failing with below error after docker run in aws ec2.
Could you make sure that you have tried mvn clean package and deployed the lastest artifacts to EC2?
Judging from stacktrace, there is a missing bean of name: entityManagerFactory. You need to refer to this bean with the correct name.
Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
Parameter 0 of constructor in com.aic.autofluence.appservice.scheduler.service.Impl.ReportFactoryImplData required a bean named 'entityManagerFactory' that could not be found.
In your code ,
#Primary
#Bean(name = "masterEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean masterEntityManagerFactory() {
// ...
#Bean(name = "tenantEntityManagerFactory")
#ConditionalOnBean(name = "datasourceBasedMultitenantConnectionProvider")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
// ...
Multiple beans are of the same type LocalContainerEntityManagerFactoryBean and of different names: masterEntityManagerFactory and tenantEntityManagerFactory.
If you wish to reference the bean by type instead of by name, you cannot do it because you have multiple beans of the same type LocalContainerEntityManagerFactoryBean. To explicitly tell Spring which bean to inject, specify the bean name per your defination.
Based on your stack trace, you referenced the bean by the name entityManagerFactory in a constructor. To fix this, you need to change the argument name from entityManagerFactory to either masterEntityManagerFactory or tenantEntityManagerFactory.
Another way to specify which bean name you wish to inject, is to use #Qualifier("beanName"). Useful Guide

Spring batch : Error creating bean with name , Gradle, Mongodb

My Application will not start. gives me an error creating a bean with the name of my file. I've searched and found similar posts to this question but they didnt seem to pertain to my error so I am hoping someone can find what may be causing this file to fail. Also, I am at a cross between two methods. Do I use the FlatFileReader or MomgoItemreader? I just need to retrieve two things from the DB firstname and lastname. I need to read the db and then write it to a file which I havent done yet. Any help would be greatly appreciated.
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Here is my class
#Configuration
#EnableBatchProcessing
public class PaymentPortalJob {
private static final Logger LOG =
LoggerFactory.getLogger(PaymentPortalJob.class);
#SuppressWarnings("unused")
#Autowired
private JobBuilderFactory jobBuilderFactory;
#SuppressWarnings("unused")
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private PaymentAuditRepository paymentAuditRepository;
// #Bean
// public FlatFileItemReader<PaymentAudit> PaymentPortalReader() {
// LOG.info("Inside PaymentPortalReader Method {}", "");
// return new FlatFileItemReaderBuilder<PaymentAudit>
().name("PaymentPortalReader")
// .delimited().names(new String[] { "rxFname", "rxLname" })
// .fieldSetMapper(new BeanWrapperFieldSetMapper<PaymentAudit>
() {
// {
// setTargetType(PaymentAudit.class);
// }
// }).build();
//
// }
#Bean
public ItemReader<PaymentAudit> reader() {
LOG.info("inside of ItemReader");
MongoItemReader<PaymentAudit> reader = new MongoItemReader<PaymentAudit>();
try {
reader.setTemplate(mongoTemplate());
} catch (Exception e) {
LOG.error(e.toString());
}
reader.setCollection("local");
return reader();
}
#Bean
public ItemProcessor<PaymentAudit, PaymentAudit> processor() {
return new PaymentPortalNOSQLProcessor();
}
#Bean
public ItemWriter<PaymentAudit> writer() {
MongoItemWriter<PaymentAudit> writer = new MongoItemWriter<PaymentAudit>();
try {
writer.setTemplate(mongoTemplate());
} catch (Exception e) {
LOG.error(e.toString());
}
writer.setCollection("paymentPortal");
return writer;
}
#Bean
Job job(JobBuilderFactory jbf, StepBuilderFactory sbf, ItemReader<? extends PaymentAudit> ir,
ItemWriter<? super PaymentAudit> iw) {
Step s1 = sbf.get("file-db").<PaymentAudit, PaymentAudit>chunk(100).reader(ir).writer(iw).build();
return jbf.get("etl").incrementer(new RunIdIncrementer()).start(s1).build();
}
#Bean
public MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new MongoClient(), "local");
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
}
appplication.yml
mongodb:
databasePort: xxxxx
databaseName: local
spring:
data:
mongodb:
host: localhost
port: xxxxx
profiles:
active: local
batch:
job:
enabled: true
Processor:
package com.spring_batchjob.job.item;
import org.springframework.batch.item.ItemProcessor;
import com.spring_batchjob.bean.PaymentAudit;
public class PaymentPortalNOSQLProcessor implements
ItemProcessor<PaymentAudit, PaymentAudit> {
#Override
public PaymentAudit process(PaymentAudit bean) throws Exception {
return bean;
}
}
repo:
package com.spring_batchjob.repository;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.spring_batchjob.bean.PaymentAudit;
#Repository
public interface PaymentAuditRepository extends
MongoRepository<PaymentAudit, String> {
// List<PaymentAudit> findByCreateDttmBetween(LocalDateTime createStart,
LocalDateTime createEnd);
List<PaymentAudit> findByRxFNameAndRxLName(String rxFName, String
rxLName);
}
Error after running app:
2018-10-26 13:26:34.256 WARN 16376 --- [ restartedMain]
ConfigServletWebServerApplicationContext : Exception encountered during
context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'paymentPortalJob': Unsatisfied dependency expressed
through field 'jobBuilderFactory'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name
'org.springframework.batch.core.configuration.annotation.
SimpleBatchConfiguration': Unsatisfied dependency expressed through field
'dataSource'; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean
with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/
DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method
failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw
exception; nested exception is
org.springframework.boot.autoconfigure.jdbc.
DataSourceProperties$DataSourceBeanCreationException: Failed to determine a
suitable driver class

Spring boot unable to read from profile specific yaml file

I was playing around with spring boot and attempted to create a profile specific configuration file. I called it application-local.yml.
And added:
spring:
profiles:
active: local
mysql:
db:
url: jdbc:mysql://localhost:3306/db?serverTimezone=UTC
driverClassName: com.mysql.jdbc.Driver
username: root
password:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
show_sql: false
server:
port: 8080
And in my DatabaseConfig.java file I attempt to read from application-local.yml and configure the database:
#Configuration
#EnableTransactionManagement
public class DatabaseConfig {
#Value("${spring.mysql.db.url}")
private String url;
#Value("${spring.mysql.db.username}")
private String userName;
#Value("${spring.mysql.db.password}")
private String password;
#Value("${spring.mysql.db.driverClassName}")
private String driverClassName;
//hibernate
#Value("${hibernate.dialect}")
private String hibernateDialect;
#Value("${hibernate.show_sql}")
private String hibernateShowSql;
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(driverClassName);
dataSource.setUsername(userName);
dataSource.setPassword(password);
return dataSource;
}
#Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(dataSource());
localContainerEntityManagerFactoryBean.setPackagesToScan("xxxx");
JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
localContainerEntityManagerFactoryBean.setJpaProperties(hibernateProperties());
return localContainerEntityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager platformTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return jpaTransactionManager;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.show_sql", hibernateShowSql);
return properties;
}
}
Now I get the error it's unable to
Error creating bean with name 'databaseConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.mysql.db.url' in value "${spring.mysql.db.url}"
but when I rename my property file to application.yml. It works perfectly fine.
I also attempted to run from the terminal using gradle command: ./gradlew -Dspring.profiles.active=local bootRun but I get the same error. It only works when I refactor the YAML file to application.yml. What am I doing wrong? I intend to have 3 profiles such as local, dev and prod.
Either add the following in your gradle file
bootRun {
profile: local
}
or try
./gradlew bootRun -Dspring.profiles.active=local
I had the same issue. I resolved it by adding
Spring:
profiles: local
Please make sure its indented properly.

Adding in a Search feature to a code swap challenge

I am participating into a code swap type challenge, for Java and Spring, and I am having some issues adding in a Search feature for this shopping list app. Before I get into depth of code, by search feature I mean search the local database, not something like google. Now I'l show the code and then explain what I'm trying to do underneath it all.
This is the error message:
2016-12-14 10:00:40.476 WARN 10452 --- [ main] o.h.b.i.SessionFactoryBuilderImpl : Unrecognized hbm2ddl_auto value : auto. Supported values include create, create-drop, update, and validate. Ignoring
2016-12-14 10:00:42.300 INFO 10452 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2016-12-14 10:00:46.009 WARN 10452 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shoppingListController': Unsatisfied dependency expressed through field 'shoppingListRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingListRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property category found for type ShoppingList!
2016-12-14 10:00:46.014 INFO 10452 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2016-12-14 10:00:46.071 INFO 10452 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2016-12-14 10:00:46.393 INFO 10452 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2016-12-14 10:00:46.455 ERROR 10452 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shoppingListController': Unsatisfied dependency expressed through field 'shoppingListRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingListRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property category found for type ShoppingList!
This is the part of the controller I am editing:
#GetMapping("/lists")
public String lists(Model model, #RequestParam(name = "srch-term", required = false) String searchTerm) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String email = auth.getName();
User u = userRepo.findOneByEmail(email);
if (searchTerm == null || "".equals(searchTerm)) {
model.addAttribute("lists", shoppingListRepo.findAllByUser(u));
} else {
ArrayList<ShoppingList> userLists = new ArrayList<ShoppingList>();
ArrayList<ShoppingList> lists = shoppingListRepo.findByCategoryContainsOrNameContainsAllIgnoreCase(searchTerm,
searchTerm);
for (ShoppingList list : lists) {
if (list.getUser() == u) {
userLists.add(list);
}
}
model.addAttribute("lists", shoppingListRepo.findAllByUser(u));
model.addAttribute("user", u);
}
return "lists";
}
This is the controller before being edited by me
#GetMapping("/lists")
public String lists(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String email = auth.getName();
User u = userRepo.findOneByEmail(email);
model.addAttribute("lists", shoppingListRepo.findAllByUser(u));
model.addAttribute("user", u);
return "lists";
}
This is my Repository
package org.elevenfifty.shoppinglist.repositories;
import java.util.ArrayList;
import org.elevenfifty.shoppinglist.beans.ShoppingList;
import org.elevenfifty.shoppinglist.beans.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ShoppingListRepository extends CrudRepository<ShoppingList, Long> {
ArrayList<ShoppingList> findAllByUser(User u);
ArrayList<ShoppingList> findByCategoryContainsOrNameContainsAllIgnoreCase(String categoryPart, String namePart);
}
Now like I said I am getting a search feature working. I am not sure where the property is in my error message I am hoping some fresh eyes can help find what I am clearly missing.
Add category field and its getters and setters to the ShoppingList class.
private String category
public void setCategory(String category){
this.category = category;
}
public String getCategory(){
return category;
}

Categories