Programmatically register EmbeddedDatabaseAutoConfiguration bean inside BeanDefinitionRegistryPostProcessor to use embedded Postgres - spring

I am registering a bean for EmbeddedDatabaseAutoConfiguration but it is never acted upon.
Is something missing for it to be processed in the same manner as if the annotation was present? I'd like to not have to declare the EmbeddedDatabaseAutoConfiguration annotation on the test class.
The BeanDefinitionRegistryPostProcessor implementation:
import io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
#Configuration
public class MyFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
#Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("postProcessBeanDefinitionRegistry before");
try {
registry.getBeanDefinition("io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration");
} catch (Exception e) {
System.out.println("Annotation missing, try programmatically register ..");
RootBeanDefinition beanDefinition = new RootBeanDefinition(EmbeddedDatabaseAutoConfiguration.class);
beanDefinition.setScope("singleton");
MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue("zonky.test.database.provider", "zonky");
beanDefinition.setPropertyValues(values);
registry.registerBeanDefinition("io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration", beanDefinition);
}
System.out.println("postProcessBeanDefinitionRegistry after");
}
#Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("postProcessBeanFactory before");
beanFactory.getBeanDefinition("io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration");
System.out.println("postProcessBeanFactory after");
}
}
Current test class:
#ActiveProfiles("test")
#SpringBootTest
// I'd like `AutoConfigureEmbeddedDatabase` to be programmatically enabled for all test classes,
// rather than requiring declarative annotation
// If the annotation is provided, the test works fine
//#AutoConfigureEmbeddedDatabase(provider = AutoConfigureEmbeddedDatabase.DatabaseProvider.ZONKY)
public class ItemServiceTest {
#Autowired private ItemService itemService;
#Test
void test_Create() {
String text = "Initial value: " + new Date();
ItemDTO itemDTO = new ItemDTO();
itemDTO.setText(text);
itemDTO = itemService.create(itemDTO);
// assert something with itemDTO ..
}
}
In the console logs below, EmbeddedDatabaseAutoConfiguration is not acted upon in the programmatic use case. Instead processing assumes a non-embedded db is present and starts initializing.
Console output when annotation is declared on test class:
Finished Spring Data repository scanning in 35 ms. Found 1 JPA repository interfaces. []
postProcessBeanDefinitionRegistry before
Generic bean: class [io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration]; scope=singleton; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null
postProcessBeanDefinitionRegistry after
Replacing 'dataSource' DataSource bean with embedded version []
postProcessBeanFactory before
postProcessBeanFactory after
trationDelegate$BeanPostProcessorChecker : Bean 'io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration' of type [io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration$$EnhancerBySpringCGLIB$$c4933b50] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) []
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] []
org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.14.Final []
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} []
i.z.t.d.p.embedded.EmbeddedPostgres : Detected a Darwin aarch64 system []
Console output when annotation is not declared on test class and programatically trying to create the Spring bean:
Finished Spring Data repository scanning in 31 ms. Found 1 JPA repository interfaces. []
postProcessBeanDefinitionRegistry before
postProcessBeanDefinitionRegistry after
o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance #Configuration bean definition 'myFactoryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'. []
postProcessBeanFactory before
postProcessBeanFactory after
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] []
org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.14.Final []
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} []
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... []
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization. []
Dependencies in build.gradle.kts:
implementation(platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES))
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-test")
implementation("io.zonky.test:embedded-postgres:2.0.2")
implementation("io.zonky.test:embedded-database-spring-test:2.2.0")

Related

How can i setup Spring Boot with two datasources (MapRepository and H2 JPARepository)?

I'm trying to set up a spring boot project with two datasources.
First datasource would be a H2 Database and second a MapRepository.
Both repositories would share the same entity.
I could manage to setup a project with two H2 databases, but when I try to setup a MapRepository instead of the second H2 datasource I get the following error:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)
2021-01-12 10:57:16.610 INFO 26672 --- [ main] ch.getonline.springtestapp.App : Starting App using Java 15.0.1 on nbbetina1 with PID 26672 (C:\Users\BetinaHiestand\eclipse20-workspace\spring-test-app\target\classes started by BetinaHiestand in C:\Users\BetinaHiestand\eclipse20-workspace\spring-test-app)
2021-01-12 10:57:16.612 INFO 26672 --- [ main] ch.getonline.springtestapp.App : The following profiles are active: dev
2021-01-12 10:57:17.070 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-01-12 10:57:17.070 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Map repositories in DEFAULT mode.
2021-01-12 10:57:17.092 INFO 26672 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data Map - Could not safely identify store assignment for repository candidate interface ch.getonline.springtestapp.storage.repositories.map.MapRepository. If you want this repository to be a Map repository, consider extending one of the following types with your repository: org.springframework.data.keyvalue.repository.KeyValueRepository.
2021-01-12 10:57:17.092 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 15 ms. Found 0 Map repository interfaces.
2021-01-12 10:57:17.094 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-01-12 10:57:17.094 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-01-12 10:57:17.111 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 14 ms. Found 1 JPA repository interfaces.
2021-01-12 10:57:17.654 INFO 26672 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-01-12 10:57:17.661 INFO 26672 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-12 10:57:17.661 INFO 26672 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.39]
2021-01-12 10:57:17.758 INFO 26672 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-12 10:57:17.758 INFO 26672 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1105 ms
2021-01-12 10:57:17.976 INFO 26672 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/dbadmin'. Database available at 'jdbc:h2:mem:db1dev'
2021-01-12 10:57:18.058 INFO 26672 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-01-12 10:57:18.099 INFO 26672 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.23.Final
2021-01-12 10:57:18.198 INFO 26672 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-01-12 10:57:18.324 INFO 26672 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate:
drop table if exists "BasicEntity" CASCADE
Hibernate:
create table "BasicEntity" (
"DNA" binary not null,
"id" varchar(255),
"type" varchar(255),
primary key ("DNA")
)
2021-01-12 10:57:18.759 INFO 26672 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-01-12 10:57:18.765 INFO 26672 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-01-12 10:57:18.787 INFO 26672 --- [ main] ch.getonline.springtestapp.App : SpringTestApplication is starting...
2021-01-12 10:57:18.931 WARN 26672 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appContext': Unsatisfied dependency expressed through field 'entityStorage'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityStorageHandler' defined in file [C:\Users\BetinaHiestand\eclipse20-workspace\spring-test-app\target\classes\ch\getonline\springtestapp\storage\handlers\EntityStorageHandler.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ch.getonline.springtestapp.storage.repositories.map.MapRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2021-01-12 10:57:18.931 INFO 26672 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-01-12 10:57:18.933 INFO 26672 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-01-12 10:57:18.944 INFO 26672 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-12 10:57:18.956 ERROR 26672 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 2 of constructor in ch.getonline.springtestapp.storage.handlers.EntityStorageHandler required a bean of type 'ch.getonline.springtestapp.storage.repositories.map.MapRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'ch.getonline.springtestapp.storage.repositories.map.MapRepository' in your configuration.
I already tried to add the ComponentScan and add a repository annotation to the MapRepository, but couldn't figure out why no bean was created for it. Both repositories are in seperate packages which are set as basePackages for the EnableMapRepositories/EnableJpaRepositories annotation. For the SQLRepository I created a configuration class with the driver properties etc. I am not sure if something like this would also be needed for the MapRepositories and couldn't find helpful documentation about it.
I am not really experienced with Spring Boot therefore the first question would be if its possible to have a setup like this? And if yes how am I supposed to configure it?
Application start:
#SpringBootApplication
#ComponentScan (basePackages = {"ch.getonline.springtestapp"})
#EntityScan("ch.getonline.springtestapp.entity.types")
#EnableMapRepositories(basePackages = "ch.getonline.springtestapp.storage.repositories.map")
#EnableJpaRepositories(basePackages = "ch.getonline.springtestapp.storage.repositories.sql", entityManagerFactoryRef = "sqlDatabaseEntityManager", transactionManagerRef = "sqlDatabaseTransactionManager")
public class App {
// Logger setup (Per class)
private static final Logger log = LoggerFactory.getLogger(App.class);
/*
* Application start
*/
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(App.class, args);
System.out.println("App context in main: " + ctx.getDisplayName());
}
MapRepository:
package ch.getonline.springtestapp.storage.repositories.map;
import org.springframework.stereotype.Repository;
import ch.getonline.springtestapp.storage.repositories.EntityRepository;
#Repository("mapRepository")
public interface MapRepository extends EntityRepository {
}
EntityRepository:
package ch.getonline.springtestapp.storage.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import ch.getonline.springtestapp.entity.types.BasicEntity;
#NoRepositoryBean
public interface EntityRepository extends CrudRepository<BasicEntity, Long>{
//Entity findByUuid(UUID id);
}
StorageHandler in which I tried to access both repositories:
package ch.getonline.springtestapp.storage.handlers;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import ch.getonline.springtestapp.AppContext;
import ch.getonline.springtestapp.entity.attribute.Attribute;
import ch.getonline.springtestapp.entity.types.BasicEntity;
import ch.getonline.springtestapp.storage.StorageHandler;
import ch.getonline.springtestapp.storage.repositories.EntityRepository;
import ch.getonline.springtestapp.storage.repositories.map.MapRepository;
import ch.getonline.springtestapp.storage.repositories.sql.SQLRepository;
/** Entity Storage
* <br>
*
* - Coordinates saving, loading, updating of Entities over different Repositories
*
*
* #author sigi
*
*/
#Component
public class EntityStorageHandler implements StorageHandler<BasicEntity, Long> {
// Logger
private static final Logger log = LoggerFactory.getLogger(EntityStorageHandler.class);
private final AppContext app;
private final Map<String, EntityRepository> repos;
EntityStorageHandler(AppContext app, SQLRepository sqlRepo, MapRepository mapRepo) {
this.app = app;
this.repos = new HashMap<String, EntityRepository>();
this.repos.put("sql", sqlRepo);
this.repos.put("map", mapRepo);
}
//StorageHandler start hook
public void run(String... args) throws Exception {
//Print all configs for the key app in the config
StringBuilder appConfig = new StringBuilder();
for(Entry<String, Object> entry : this.app.getConfig().entrySet()) {
appConfig.append("\nkey: " + entry.getKey() + " value: " + entry.getValue());
}
log.info(appConfig.toString());
//Write demo Entity into db
BasicEntity e1 = new BasicEntity();
e1.setId("1");
e1.setType("Type1");
this.repos.get("sql").save(e1);
BasicEntity e2 = new BasicEntity();
e2.setId("2");
e2.setType("Type2");
this.repos.get("sql").save(e2);
BasicEntity e3 = new BasicEntity();
e3.setId("3");
e3.setType("Type3");
this.repos.get("map").save(e2);
}
}
BasicEntity:
package ch.getonline.springtestapp.entity.types;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
import ch.getonline.springtestapp.entity.GenericEntity;
/**
* Basic Entity Implementation
*
* #author sigi
*
*/
#Entity
#KeySpace("basicEntities")
public class BasicEntity extends GenericEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
UUID DNA;
}
SQLConfiguration:
package ch.getonline.springtestapp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
#Configuration
public class SQLConfiguration {
#Autowired
private Environment env;
public SQLConfiguration() {
super();
}
#Primary
#Bean
public LocalContainerEntityManagerFactoryBean sqlDatabaseEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(sqlDataSource());
em.setPackagesToScan("ch.getonline.springtestapp.entity.types");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
properties.put("hibernate.dialect", env.getProperty("spring.jpa.database-platform"));
properties.put("hibernate.jdbc.batch_size", env.getProperty("spring.jpa.properties.hibernate.jdbc.batch_size"));
properties.put("hibernate.order_inserts", env.getProperty("spring.jpa.properties.hibernate.order_inserts"));
properties.put("hibernate.order_updates", env.getProperty("spring.jpa.properties.hibernate.order_updates"));
properties.put("hibernate.jdbc.batch_versioned_data", env.getProperty("spring.jpa.properties.hibernate.jdbc.batch_versioned_data"));
properties.put("hibernate.generate_statistics", env.getProperty("spring.jpa.properties.hibernate.generate_statistics"));
properties.put("hibernate.id.new_generator_mappings", env.getProperty("spring.jpa.properties.hibernate.id.new_generator_mappings"));
properties.put("hhibernate.cache.use_second_level_cache", env.getProperty("spring.jpa.properties.hibernate.cache.use_second_level_cache"));
properties.put("hibernate.globally_quoted_identifiers", env.getProperty("spring.jpa.properties.hibernate.globally_quoted_identifiers"));
properties.put("hibernate.format_sql", env.getProperty("spring.jpa.properties.hibernate.format_sql"));
properties.put("hibernate.show_sql", env.getProperty("spring.jpa.properties.hibernate.show_sql"));
properties.put("hibernate.use_sql_comments", env.getProperty("spring.jpa.properties.hibernate.use_sql_comments"));
properties.put("hibernate.type", env.getProperty("spring.jpa.properties.hibernate.type"));
properties.put("hibernate.naming.physical-strategy", env.getProperty("spring.jpa.hibernate.naming.physical-strategy"));
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource sqlDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
#Primary
#Bean
public PlatformTransactionManager sqlDatabaseTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(sqlDatabaseEntityManager().getObject());
return transactionManager;
}
}
SQLRepository
package ch.getonline.springtestapp.storage.repositories.sql;
import ch.getonline.springtestapp.storage.repositories.EntityRepository;
public interface SQLRepository extends EntityRepository {
}
application.yml
#Debug mode
debug: false
#External config
spring:
#Basic setup
profiles.active: dev
config:
import: optional:classpath:config/app.properties, optional:classpath:config/config.yml
#Localization
messages:
basename: config.i18n.messages
#db
h2:
console:
path: /dbadmin
enabled: true
settings:
web-allow-others: true
datasource:
username: inmemory
password: inmemory
driverClassName: org.h2.Driver
port: 8080
#jpa
jpa:
hibernate:
ddl-auto: create
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
id:
new_generator_mappings: true
cache:
use_second_level_cache: true
order_inserts: true
order_updates: true
globally_quoted_identifiers: true
generate_statistics: false
show_sql: true
format_sql: true
use_sql_comments: true
type: trace
jdbc:
batch_size: 500
batch_versioned_data: false
tmp:
use_jdbc_metadata_defaults: false
database-platform: org.hibernate.dialect.H2Dialect
As written in my comment, it's quite unusual to use two different datasources with one spring boot service. But here are cases where this might be necessary, and here is how to achieve it in a clean way:
Keep in mind, my answer is mostly taken from that Baeldung tutorial
Consider having a datasource like this:
spring.datasource.jdbcUrl = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
Now, we want to add a second one, preferably with the same syntax:
spring.second-datasource.jdbcUrl = [url]
spring.second-datasource.username = [username]
spring.second-datasource.password = [password]
To use both configurations simoultanously, we just create two configuration classes with a Datasource Bean - pay attention to the prefix annotation:
#Configuration
#PropertySource({"classpath:persistence-multiple-db-boot.properties"})
#EnableJpaRepositories(
basePackages = "com.baeldung.multipledb.dao.user",
entityManagerFactoryRef = "userEntityManager",
transactionManagerRef = "userTransactionManager")
public class PersistenceUserAutoConfiguration {
#Primary
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSource userDataSource() {
return DataSourceBuilder.create().build();
}
// userEntityManager bean
// userTransactionManager bean
}
#Configuration
#PropertySource({"classpath:persistence-multiple-db-boot.properties"})
#EnableJpaRepositories(
basePackages = "com.baeldung.multipledb.dao.product",
entityManagerFactoryRef = "productEntityManager",
transactionManagerRef = "productTransactionManager")
public class PersistenceProductAutoConfiguration {
#Bean
#ConfigurationProperties(prefix="spring.second-datasource")
public DataSource productDataSource() {
return DataSourceBuilder.create().build();
}
// productEntityManager bean
// productTransactionManager bean
}
You could imo just create one configuration class and provide both beans in that one.
For more information see Spring JPA – Multiple Databases

Springboot : failed while scanning for beans

I am trying to understand a concept in springboot.
I have project structure as mentioned below. There are two packages and I have one class in each package.
src/main/java
> com.emerald.paymentengine
ApplicationRun.java
> com.emerald.paymentengine.config
DataSourceDbConfig.java
When I am trying to run the ApplicationRun.java following above structure, I am getting below error :
Error:
2020-08-19 01:33:08.673 INFO 30128 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-19 01:33:08.673 INFO 30128 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-19 01:33:08.749 INFO 30128 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-19 01:33:08.750 INFO 30128 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 657 ms
2020-08-19 01:33:08.779 WARN 30128 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationRun': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-08-19 01:33:08.781 INFO 30128 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-19 01:33:08.791 INFO 30128 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-19 01:33:08.883 ERROR 30128 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.emerald.paymentengine.ApplicationRun required a bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' that could not be found.
Action:
Consider defining a bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' in your configuration.
But when I moved DataSourceDbConfig.java in the same package as mentioned below, it's running and I am getting below output :
src/main/java
> com.emerald.paymentengine
ApplicationRun.java
DataSourceDbConfig.java
Output :
2020-08-19 01:37:24.726 INFO 34364 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-19 01:37:24.726 INFO 34364 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-19 01:37:24.810 INFO 34364 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-19 01:37:24.810 INFO 34364 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 722 ms
2020-08-19 01:37:24.849 INFO 34364 --- [ restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: static com.emerald.paymentengine.DataSourceDbConfig com.emerald.paymentengine.ApplicationRun.dbConfig
Connection established !!
2020-08-19 01:37:24.981 INFO 34364 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-19 01:37:25.116 INFO 34364 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-08-19 01:37:25.140 INFO 34364 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''
2020-08-19 01:37:25.148 INFO 34364 --- [ restartedMain] c.emerald.paymentengine.ApplicationRun : Started ApplicationRun in 1.335 seconds (JVM running for 2.406)
I was thinking #SpringBootApplication will automatically scan the main and subpackages and will be able to pick the required bean. How can I make it work by placing Config.java file in different package as mentioned in the very first scenario?
Code :
ApplicationRun.java
package com.emerald.paymentengine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ApplicationRun {
#Autowired
static
DataSourceDbConfig dbConfig;
public ApplicationRun(DataSourceDbConfig dbConfig){
ApplicationRun.dbConfig = dbConfig ;
}
public static void main(String[] args) {
SpringApplication.run(ApplicationRun.class, args);
dbConfig.dataSource();
}
}
DataSourceDbConfig.java
package com.emerlad.paymentengine.config;;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
#Component
#Configuration
#ConfigurationProperties("spring.datasource")
public class DataSourceDbConfig {
#Value("${spring.datasource.url}")
private String dbUrl;
#Value("${spring.datasource.username}")
private String dbUser;
#Value("${spring.datasource.secure}")
private String dbPasswrd;
#Bean
public DataSource dataSource() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPasswrd);
dataSource.setURL(dbUrl);
System.out.println("Connection established !!");
} catch (SQLException e) {
System.out.println("An issue occured while establishing connection !!");
e.printStackTrace();
}
return dataSource;
}
}
I'll be honest, I do not understand what it is that you want to accomplish, but this is how to get the DataSource bean in your main method:
ApplicationRun.java:
package com.emerald.paymentengine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.emerlad.paymentengine.config.DataSourceDbConfig;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
#SpringBootApplication
#Import(DataSourceDbConfig.class)
public class ApplicationRun {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ApplicationRun.class, args);
DataSource dataSource = context.getBean(DataSource.class)
}
}
DataSourceDbConfig.java:
package com.emerlad.paymentengine.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
#Configuration
#ConfigurationProperties("spring.datasource")
public class DataSourceDbConfig {
#Value("${spring.datasource.url}")
private String dbUrl;
#Value("${spring.datasource.username}")
private String dbUser;
#Value("${spring.datasource.secure}")
private String dbPasswrd;
#Bean
public DataSource dataSource() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPasswrd);
dataSource.setURL(dbUrl);
System.out.println("Connection established !!");
} catch (SQLException e) {
System.out.println("An issue occured while establishing connection !!");
e.printStackTrace();
}
return dataSource;
}
}
class DataSourceDbConfig - using #Configuration includes #Component, so you can get rid of it
class ApplicationRun - I would keep it simple and remove the DataSourceDbConfig
#SpringBootApplication
public class ApplicationRun {
public static void main(String[] args) {
ApplicationContext appContext = SpringApplication.run(ApplicationRun.class, args);
// Getting datasource from application context.
DataSource dataSource = appContext.getBean(DataSource.class);
}
}

Karate: How to configure karate mock-servlet using a YAML file instead of application.properties? [duplicate]

This question already has an answer here:
Karate Spring Integration
(1 answer)
Closed 1 year ago.
We have a Spring Boot project which uses an application.yml file to configure the spring context for things like datasource, rabbitmq etc.
The YAML file can be loaded in the karate-config.js to pick-up the baseUrl and that works fine.
function fn() {
var env = karate.env; // get system property 'karate.env'
karate.log('karate.env system property was:', env);
if (!env) {
env = 'dev';
}
karate.log('karate environment set to:', env);
var config = karate.read('classpath:application.yml');
karate.log('baseUrl configured for API tests: '+config.baseUrl)
if (env == 'dev') {
var Factory = Java.type('MockSpringMvcServlet');
karate.configure('httpClientInstance', Factory.getMock());
//var result = karate.callSingle('classpath:demo/headers/common-noheaders.feature', config);
} else if (env == 'stg') {
// customize
} else if (env == 'prod') {
// customize
}
return config;
}
The Mock Spring MVC servlet class taken from the karate mock servlet demo github project:
/**
* #author pthomas3
*/
public class MockSpringMvcServlet extends MockHttpClient {
private final Servlet servlet;
private final ServletContext servletContext;
public MockSpringMvcServlet(Servlet servlet, ServletContext servletContext) {
this.servlet = servlet;
this.servletContext = servletContext;
}
#Override
protected Servlet getServlet(HttpRequestBuilder request) {
return servlet;
}
#Override
protected ServletContext getServletContext() {
return servletContext;
}
private static final ServletContext SERVLET_CONTEXT = new MockServletContext();
private static final Servlet SERVLET;
static {
SERVLET = initServlet();
}
private static Servlet initServlet() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(MockConfig.class);
context.setServletContext(SERVLET_CONTEXT);
DispatcherServlet servlet = new DispatcherServlet(context);
ServletConfig servletConfig = new MockServletConfig();
try {
servlet.init(servletConfig);
} catch (Exception e) {
throw new RuntimeException(e);
}
return servlet;
}
public static MockSpringMvcServlet getMock() {
return new MockSpringMvcServlet(SERVLET, SERVLET_CONTEXT);
}
}
However, the MockConfig.class fails on the EnableAutoConfiguration annotation:
#Configuration
#EnableAutoConfiguration
// #PropertySource("classpath:application.yml") // only for key/value pair .properties files and not YAML
public class MockConfig {
// Global Exception Handler ...
// Services ...
// Controllers ...
#Bean
public NumbersAPI numbersAPI() {
return new NumbersAPI();
}
}
The exception is:
2019-04-23 15:13:21.297 INFO --- [ main] com.intuit.karate : karate.env system property was: null
2019-04-23 15:13:21.306 INFO --- [ main] com.intuit.karate : karate environment set to: dev
2019-04-23 15:13:21.429 INFO --- [ main] com.intuit.karate : baseUrl configured for API tests: http://localhost:50000
2019-04-23 15:13:21.469 INFO --- [ main] o.s.mock.web.MockServletContext : Initializing Spring FrameworkServlet ''
2019-04-23 15:13:21.469 INFO --- [ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet '': initialization started
2019-04-23 15:13:21.496 INFO --- [ main] .s.AnnotationConfigWebApplicationContext : Refreshing WebApplicationContext for namespace '-servlet': startup date [Tue Apr 23 15:13:21 EDT 2019]; root of context hierarchy
2019-04-23 15:13:21.535 INFO --- [ main] .s.AnnotationConfigWebApplicationContext : Registering annotated classes: [class MockConfig]
2019-04-23 15:13:22.215 INFO --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Dbcp2; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Dbcp2.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]]
2019-04-23 15:13:22.330 WARN --- [ main] o.s.b.a.AutoConfigurationPackages : #EnableAutoConfiguration was declared on a class in the default package. Automatic #Repository and #Entity scanning is not enabled.
2019-04-23 15:13:22.714 INFO --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration' of type [org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration$$EnhancerBySpringCGLIB$$cafe2407] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-23 15:13:23.212 WARN --- [ main] .s.AnnotationConfigWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; 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$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2019-04-23 15:13:23.215 ERROR --- [ main] o.s.web.servlet.DispatcherServlet : Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; 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$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
I've used the documentation from the karate mock-servlet github project as guidance to make other karate tests work successfully, but I don't know how to configure the spring context for our karate tests using an application YAML file.
The #PropertySource only supports properties files as you already found out.
Have a look at the following SOF question:
Spring #PropertySource using YAML
Hope this helps.
I was able to get the application.yml file to be respected and loaded by Spring by making the following changes:
Add a YamlPropertySourceFactory util class to the test package:
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
#Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
and
Referencing the above in the #PropertySource annotation in the MockConfig class as follows:
#Configuration
#EnableAutoConfiguration
#PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:application.yml")
public class MockConfig {
// Global Exception Handler ...
#Bean
public ExampleAPIExceptionHandler exampleAPIExceptionHandler() {
return new ExampleAPIExceptionHandler();
}
// Services ...
// Controllers ...
#Bean
public NumbersAPI numbersAPI() {
return new NumbersAPI();
}
}
The Spring context loads and all karate tests pass.
If there is a simpler way to load a YAML file as a Spring context using Karate, then please post it. For now, this will work.
Reference: Use #PropertySource with YAML files

Spring boot JUNIT test fails for service test

I am trying to perform a Junit 4 test from a service in a spring boot application and I keep getting an entityManagerFactory its with init.
I also want connect using my application.properties file, but it wants to connect using the embedded hsqldb.
Can someone point me in the right direction?
Below is the pertinent code:
APPLICATION.PROPERTIES:
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database "netgloo_blog"
spring.datasource.url = jdbc:mysql://localhost:3306/finra?useSSL=false
# Username and password
spring.datasource.username = finra
spring.datasource.password = finra
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
MAIN:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#EnableTransactionManagement
#ComponentScan(basePackages = {"com.example"})
#EntityScan(basePackages = {"com.example.entity"})
//#ImportResource("classpath:application.properties")
//#Configuration
//#EnableAutoConfiguration
//#ComponentScan
//#EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
ENTITY:
package com.example.entity;
import java.io.Serializable;
public interface UserInterface extends Serializable{
public long getId();
public long setId(long value);
public String getEMail();
public void setEmail( String value );
public String getName();
public void setName(String value);
}
package com.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
//import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
//#Table(name = "users")
#Table(
uniqueConstraints = {
#UniqueConstraint(columnNames = {"email"})
}
)
public class User implements UserInterface {
/**
*
*/
private static final long serialVersionUID = -507606192667894785L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotNull
private String email;
#NotNull
private String name;
#Override
public long getId() {
// TODO Auto-generated method stub
return id;
}
#Override
public long setId(long value) {
// TODO Auto-generated method stub
return id = value;
}
#Override
public String getEMail() {
// TODO Auto-generated method stub
return email;
}
#Override
public void setEmail(String value) {
// TODO Auto-generated method stub
email = value;
}
#Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
#Override
public void setName(String value) {
// TODO Auto-generated method stub
name = value;
}
}
DAO/REPOSITORY:
package com.example.dao;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import com.example.entity.User;
#Transactional
public interface UserDao extends CrudRepository<User, Long> {
public User findByEmail( String email );
public void setUserDao(UserDao userDao);
}
SERVICE:
package com.example.service;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.UserDao;
import com.example.entity.User;
#Service("userService")
public class UserService {
private final Logger log = Logger.getLogger (this.getClass());
#Autowired UserDao userDao;
public void setUserDao( UserDao userDao ){
this.userDao = userDao;
}
public List<User> findAll(){
return (List<User>) userDao.findAll();
}
public User findOne( long id ){
return userDao.findOne(id);
}
public User getByEmail(String email) throws Exception{
String userId = null;
User user = null;
try{
user = userDao.findByEmail(email);
userId = String.valueOf(user.getId());
}catch(Exception e){
log.error("User not found");
e.printStackTrace();
throw new Exception(e);
}
log.info("The user id is: " + userId);
return user;
}
public User create( String email, String name ){
User user = null;
try{
user = new User();
user.setEmail(email);
user.setName(name);
userDao.save(user);
}catch( Exception e ){
log.error("Error creating the user: " + e.getMessage());
}
log.info("User id: " + user.getId() + " saved.");
return user;
}
public User updateUser(long id, String email, String name ){
User user = null;
try{
user = userDao.findOne(id);
user.setEmail(email);
user.setName(name);
userDao.save(user);
}catch( Exception e ){
log.error("Error updating the user: " + e.getMessage());
}
return user;
}
public User delete( long id ) throws Exception{
User user = null;
user = userDao.findOne(id);
userDao.delete(user);
return user;
}
}
TEST:
/**
*
*/
package com.example.service;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.example.DemoApplication;
import com.example.dao.UserDao;
import com.example.entity.User;
/**
* #author denisputnam
*
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = DemoApplication.class)
//#SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
//#SpringBootConfiguration
#DataJpaTest
#Transactional
public class UserServiceTest {
#Autowired
private UserDao userDao;
private UserService userService;
// #Autowired
// public void setUserService( UserService userService ){
// this.userService = userService;
// }
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
// userDao = EasyMock.createMock(UserDao.class);
//
userService = new UserService();
userService.setUserDao(userDao);
// testEntityManager = new TestEntityManager(emf);
// this.testContextManager = new TestContextManager(getClass());
// this.testContextManager.prepareTestInstance(this);
}
/**
* Test method for {#link com.example.service.UserService#findAll()}.
*/
#Test
public void testFindAll() {
// EasyMock.reset(userDao);
// final List<User> users = new ArrayList<User>();
// EasyMock.expect(userDao.findAll()).andReturn(users);
// EasyMock.replay(userDao);
// EasyMock.verify(userDao);
// Assert.notEmpty(users, "findAll() failed.");
// User user = new User();
// user.setEmail("bogus#bogus.com");
// user.setName("bogus");
// UserService userService = new UserService();
// this.setUserService(userService);
User user = this.userService.create("bogus#bogus.com", "bogus");
final List<User> users = (List<User>) this.userDao.findAll();
Assert.notEmpty(users, "Found no users.");
}
/**
* Test method for {#link com.example.service.UserService#findOne(long)}.
*/
#Test
public void testFindOne() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#getByEmail(java.lang.String)}.
*/
#Test
public void testGetByEmail() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#create(java.lang.String, java.lang.String)}.
*/
#Test
public void testCreate() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#updateUser(long, java.lang.String, java.lang.String)}.
*/
#Test
public void testUpdateUser() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#delete(long)}.
*/
#Test
public void testDelete() {
fail("Not yet implemented");
}
}
SHOULD HAVE INCLUDED THIS:
2017-04-02 16:30:00.627 INFO 93661 --- [ main] com.example.service.UserServiceTest : Starting UserServiceTest on Deniss-IMAC.home with PID 93661 (started by denisputnam in /Users/denisputnam/git/springboot/demo)
2017-04-02 16:30:00.627 INFO 93661 --- [ main] com.example.service.UserServiceTest : No active profile set, falling back to default profiles: default
2017-04-02 16:30:00.630 INFO 93661 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#3111631d: startup date [Sun Apr 02 16:30:00 EDT 2017]; root of context hierarchy
2017-04-02 16:30:00.694 INFO 93661 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'userService' with a different definition: replacing [Generic bean: class [com.example.service.UserService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/Users/denisputnam/git/springboot/demo/target/classes/com/example/service/UserService.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userServiceTest.Config; factoryMethodName=userService; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/example/service/UserServiceTest$Config.class]]
2017-04-02 16:30:00.705 INFO 93661 --- [ main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2017-04-02 16:30:00.705 INFO 93661 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-04-02 16:30:00.705 WARN 93661 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance #Configuration bean definition 'embeddedDataSourceBeanFactoryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-04-02 16:30:00.740 INFO 93661 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:77b77b83-0034-41be-ab58-3f5d9490ea80', username='sa'
2017-04-02 16:30:00.805 INFO 93661 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-02 16:30:00.805 INFO 93661 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-04-02 16:30:00.810 INFO 93661 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-02 16:30:00.825 INFO 93661 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2017-04-02 16:30:00.827 INFO 93661 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.828 INFO 93661 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.829 WARN 93661 --- [ 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 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-04-02 16:30:00.829 INFO 93661 --- [ main] utoConfigurationReportLoggingInitializer :
STACK:
2017-04-02 16:05:44.625 ERROR 92739 --- [ main] o.s.boot.SpringApplication : Application startup failed
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 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
I found the solution here:
spring boot configuration example

Spring boot cassandra integration #EnableCassandraRepositories not generating implementation for Cassandra Repository

I am trying to integrate cassandra with Spring boot using spring-data-cassandra.
Application.java
package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
CassandraConfiguration.java
package conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
#Configuration
#EnableCassandraRepositories("dao")
public class CassandraConfiguration extends AbstractCassandraConfiguration {
#Bean
#Override
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints("localhost");
cluster.setPort(9042);
return cluster;
}
#Override
protected String getKeyspaceName() {
return "mykeyspace";
}
#Bean
#Override
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
}
UserDao.java
package dao;
import hello.User;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
public interface UserDao extends CassandraRepository<User> {
#Query("select * from users where fname = ?0")
Iterable findByFname(String fname);
}
RestController.java
package hello;
import dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserController {
#Autowired
UserDao userDao;
#RequestMapping("/greeting")
public Iterable<User> getInfo(#RequestParam(value="name", defaultValue="Hello") String name, #RequestParam(value="lname", defaultValue="World") String lname) {
return userDao.findByFname(name) ;//new User(counter.incrementAndGet(),name, lname);
}
}
User.java
package hello;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
#Table
public class User {
#PrimaryKey
private final long id;
#Column
private final String fname;
#Column
private final String lname;
public User(long id, String fname, String lname) {
this.id = id;
this.fname = fname;
this.lname = lname;
}
public long getId() {
return id;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
}
Behind the scene #EnableCassandraConfiguration should create an implementation for UserDao interface. but seems like it is not doing so for some reason. Logs are not that useful to tell specific mistake i am making here. Still for help i am posting it here.
2015-02-11 12:10:58.424 INFO 7828 --- [ main] hello.Application : Starting Application on HOTCPC9941 with PID 7828 (C:\Users\prashant.tiwari\Documents\NetBeansProjects\DemoApp\target\classes started by prashant.tiwari in C:\Users\prashant.tiwari\Documents\NetBeansProjects\DemoApp)
2015-02-11 12:10:58.459 INFO 7828 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4f5737ca: startup date [Wed Feb 11 12:10:58 GMT 2015]; root of context hierarchy
2015-02-11 12:10:59.141 INFO 7828 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-02-11 12:10:59.865 INFO 7828 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2015-02-11 12:11:00.035 INFO 7828 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2015-02-11 12:11:00.036 INFO 7828 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.57
2015-02-11 12:11:00.127 INFO 7828 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2015-02-11 12:11:00.128 INFO 7828 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1672 ms
2015-02-11 12:11:00.555 INFO 7828 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2015-02-11 12:11:00.557 INFO 7828 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-02-11 12:11:00.682 WARN 7828 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: dao.UserDao hello.UserController.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: dao.UserDao hello.UserController.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:522)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298)
... 16 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] 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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:967)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:494)
... 18 common frames omitted
Seems that your Dao class doesn't get registered into the context. I'd say it is missing an appropriate annotation like #Repository.
Additionally your Application class is living in the hello package and without any further configuration is only scanning for components below it. That is why it is not finding the CassandraConfiguration (living in conf). And this is then also not scanning the dao package.
I was also facing the same problem for auto wiring the class which uses cassandra support, try adding:
#EnableCassandraRepositories(basePackages="package path where where is ur bean")

Resources