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

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")

Related

Programmatically register EmbeddedDatabaseAutoConfiguration bean inside BeanDefinitionRegistryPostProcessor to use embedded Postgres

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")

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

Not able to persist Object in a table using Hibernate

I am consuming API with the help of Spring Boot and trying to persist the same in MySQL database by using Hibernate, but getting error doing so, I have tried things but somehow I am stuck with it.
Stack Trace
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.5.RELEASE)
2018-09-20 00:51:26 INFO com.diwakar.GroupBeema - Starting GroupBeema on LP-PC0MQFY6 with PID 13084 (started by diwakar_b in C:\Diwakar Playground\GroupBeema)
2018-09-20 00:51:26 INFO com.diwakar.GroupBeema - No active profile set, falling back to default profiles: default
2018-09-20 00:51:26 INFO o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#12d4bf7e: startup date [Thu Sep 20 00:51:26 IST 2018]; root of context hierarchy
2018-09-20 00:51:27 INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c2e2ffe4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-09-20 00:51:28 INFO o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
2018-09-20 00:51:28 INFO o.a.catalina.core.StandardService - Starting service [Tomcat]
2018-09-20 00:51:28 INFO o.a.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.5.34
2018-09-20 00:51:28 INFO o.a.c.core.AprLifecycleListener - The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_172\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_172/bin/server;C:/Program Files/Java/jre1.8.0_172/bin;C:/Program Files/Java/jre1.8.0_172/lib/amd64;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Windows\CCM;C:\Program Files\PuTTY\;C:\Program Files\Git\cmd;C:\Program Files\Gradle\gradle-4.5.1\bin;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Users\diwakar_b\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Docker Toolbox;C:\Users\diwakar_b\Downloads\eclipse-jee-photon-R-win32-x86_64\eclipse;;.]
2018-09-20 00:51:29 INFO o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2018-09-20 00:51:29 INFO o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 2997 ms
2018-09-20 00:51:29 INFO o.s.b.w.s.ServletRegistrationBean - Servlet dispatcherServlet mapped to [/]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-09-20 00:51:29 INFO o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
2018-09-20 00:51:29 WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hibernateUtil': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
2018-09-20 00:51:29 INFO o.a.catalina.core.StandardService - Stopping service [Tomcat]
2018-09-20 00:51:29 INFO o.s.b.a.l.ConditionEvaluationReportLoggingListener -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-20 00:51:29 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hibernateUtil': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265)
at com.diwakar.GroupBeema.main(GroupBeema.java:10)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:590)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
... 31 common frames omitted
Caused by: java.lang.NullPointerException: null
at com.diwakar.hibernate.HibernateUtil.getSessionfactory(HibernateUtil.java:19)
at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353.CGLIB$getSessionfactory$0(<generated>)
at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353$$FastClassBySpringCGLIB$$adc355b2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:365)
at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353.getSessionfactory(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 32 common frames omitted
GroupBeema Class
package com.diwakar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class GroupBeema{
public static void main(String[] args) {
SpringApplication.run(GroupBeema.class, args);
}
}
InsurerController
package com.diwakar.insurer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.diwakar.hibernate.InsurerDao;
#RestController
public class InsurerController {
#Autowired
public InsurerService insurerService;
#Autowired
private InsurerDao insurerDao;
#RequestMapping("/insure")
public List<Insurer> getInsurersInfo() {
List<Insurer> list = insurerService.getAllInsurer();
//insurerService.createTable(list);
insurerDao.createInsurer(list);
return list;
}
}
InsurerService
package com.diwakar.insurer;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
#Service
public class InsurerService {
public List<Insurer> getAllInsurer( ) {
List<Insurer> list = new ArrayList<Insurer>();
try {
Client client = Client.create();
WebResource webResource = client.resource("https://termlife.policybazaar.com/api/v1/quotes");
String input = "//some json data"
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
JSONArray jsonArray = new JSONArray(output);
for(int n = 0; n < jsonArray.length(); n++) {
JSONObject obj = jsonArray.getJSONObject(n);
Insurer ins = new Insurer();
ins.setBasicPremium(obj.getInt("BasicPremium"));
ins.setE2EName(obj.getString("E2EName"));
ins.setE2ESupplier(obj.getString("E2ESupplier"));
list.add(ins);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
HibernateUtil
package com.diwakar.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class HibernateUtil {
#Autowired
private EntityManagerFactory entityManagerFactory;
#Bean
public SessionFactory getSessionfactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
//throw new NullPointerException("factory is not hibernate factory.!!");
System.out.println("Exception in getSessionfactory method..");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
InsurerDAO
package com.diwakar.hibernate;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.diwakar.insurer.Insurer;
#Repository
public class InsurerDao {
#Autowired
private SessionFactory sessionFactory;
public void createInsurer(List<Insurer> insurer) {
Session session = null;
//SessionFactory sessionFactory = null;
try {
//sessionFactory = new Configuration().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
Integer i = (Integer) session.save(insurer);
System.out.println("Insurer table is created with " + i + " records..!!");
session.getTransaction().commit();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Application properties
//assume everything is correct
The problem with your code is that SessionFactory is a subinterface to EntityManagerFactory. Even if you change that to EntityManager, it won't work as EntityManager is dependent on EntityManagerFactory and therefore, the method for it is called first in the lifecycle at startup. Could you please explain, why you need the SessionFactory? If you want to have the EntityManager, you can just inject that by using #PersistenceContext in your services.
You cannot autowire in a configuration class put pass your dependencies as parameters
So your HibernateUtil must look like:
#Configuration
public class HibernateUtil {
#Bean
public SessionFactory getSessionfactory(EntityManagerFactory entityManagerFactory) {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
//throw new NullPointerException("factory is not hibernate factory.!!");
System.out.println("Exception in getSessionfactory method..");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}

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: How to externalize JDBC datasource configuration?

I have following Spring Boot controller code that works. (Some sensitive text was replaced)
package com.sample.server;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class DetailReportController
{
#RequestMapping(value="/report/detail", method=RequestMethod.GET)
public List<UFGroup> detailReport()
{
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
dataSource.setUrl("jdbc:jtds:sqlserver://111.11.11.11/DataBaseName;user=sa;password=password");
JdbcTemplate jt = new JdbcTemplate(dataSource);
List<UFGroup> results = jt.query(
"select NID, SCode, SName from UFGroup",
new RowMapper<UFGroup>()
{
#Override
public UFGroup mapRow(ResultSet rs, int rowNum) throws SQLException
{
return new UFGroup(rs.getInt("NID"), rs.getString("SCode"),
rs.getString("SName"));
}
});
return results;
}
private static class UFGroup
{
public int nid;
public String scode;
public String sname;
public UFGroup(int nid, String scode, String sname)
{
this.nid = nid;
this.scode = scode;
this.sname = sname;
}
}
}
Now I want to externalize the configuration of the datasource.
That is, BasicDataSource class, driver class name, datasource URL should be placed into application.properties.
How can I do that?
BTW, I am a newbie of Spring, Spring Boot and even Java Beans. All I have is some Java programming experience, mainly for mobile devices. I've spent a few days to study Spring Boot environment, but I was literally overwhelmed.
So please, give me the exact instruction with concrete example.
UPDATE:
when I applied the answer of M. Deinum, following error occured when I ran the application:
2013-11-18 19:37:54.789 INFO 6868 --- [ main] com.logicplant.uflow.server.Application : Starting Application on zeo-PC with PID 6868 (C:\Projects\uFlow\Dev\Server\Spring\uFlowServer\build\libs\uFlowServer-1.0.0.jar started by zeo)
2013-11-18 19:37:54.830 INFO 6868 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#7f83698f: startup date [Mon Nov 18 19:37:54 KST 2013]; root of context hierarchy
2013-11-18 19:37:55.931 INFO 6868 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2013-11-18 19:37:55.932 INFO 6868 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.42
2013-11-18 19:37:56.009 INFO 6868 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2013-11-18 19:37:56.010 INFO 6868 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1183 ms
2013-11-18 19:37:56.165 INFO 6868 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2013-11-18 19:37:56.165 INFO 6868 --- [ost-startStop-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2013-11-18 19:37:56.242 INFO 6868 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-11-18 19:37:56.388 INFO 6868 --- [ost-startStop-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/report/detail],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.List<com.logicplant.uflow.server.DetailReportController$UFGroup> com.logicplant.uflow.server.DetailReportController.detailReport()
2013-11-18 19:37:56.438 INFO 6868 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-11-18 19:37:56.439 INFO 6868 --- [ost-startStop-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-11-18 19:37:56.788 INFO 6868 --- [ost-startStop-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 622 ms
2013-11-18 19:37:56.881 INFO 6868 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'detailReportController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate com.logicplant.uflow.server.DetailReportController.jt; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1139)
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:299)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:665)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:509)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:278)
at com.logicplant.uflow.server.Application.main(Application.java:17)
... 6 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.core.JdbcTemplate com.logicplant.uflow.server.DetailReportController.jt; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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:505)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 20 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] 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:1051)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:919)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:820)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:477)
... 22 more
For reference, the content of build.grade file (I use Gradle) is as follows: (following M. Deinum's suggestion, I removed the dependency for org.apache.commons.dbcp.)
buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M5")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'uFlowServer'
version = '1.0.0'
}
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-snapshot" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M5")
compile("com.fasterxml.jackson.core:jackson-databind")
compile("org.springframework:spring-jdbc:4.0.0.M3")
runtime("net.sourceforge.jtds:jtds:1.3.1")
testCompile("junit:junit:4.11")
}
task wrapper(type: Wrapper) {
gradleVersion = '1.8'
}
And this is Application.java file, which is the main source file.
package com.sample.server;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application
{
public static void main(String args[])
{
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
app.run(args);
}
}
What can be done for the error?
UPDATE:
As M. Deinum suggested, when I changed build.gradle file as follows, the application worked!
buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M6")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'uFlowServer'
version = '1.0.0'
}
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-snapshot" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M6")
compile("org.springframework.boot:spring-boot-starter-jdbc:0.5.0.M6")
compile("com.fasterxml.jackson.core:jackson-databind")
runtime("net.sourceforge.jtds:jtds:1.3.1")
testCompile("junit:junit:4.11")
}
task wrapper(type: Wrapper) {
gradleVersion = '1.8'
}
Change your controller to the following
#RestController
public class DetailReportController {
#Autowired
private JdbcTemplate jt;
#RequestMapping(value="/report/detail", method=RequestMethod.GET)
public List<UFGroup> detailReport() {
List<UFGroup> results = jt.query(
"select NID, SCode, SName from UFGroup",
new RowMapper<UFGroup>(){
#Override
public UFGroup mapRow(ResultSet rs, int rowNum) throws SQLException {
return new UFGroup(rs.getInt("NID"), rs.getString("SCode"), rs.getString("SName"));
}
});
return results;
}
private static class UFGroup
{
public int nid;
public String scode;
public String sname;
public UFGroup(int nid, String scode, String sname)
{
this.nid = nid;
this.scode = scode;
this.sname = sname;
}
}
}
In src/main/resources add an application.properties with the following
spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
spring.datasource.url=jdbc:jtds:sqlserver://111.11.11.11/DataBaseName
spring.datasource.username=sa
spring.datasource.password=password
And simply start your application. No xml needed. Spring boot will create the DataSource and will add a default JdbcTemplate instance.
Tip: Remove the dependency for org.apache.commons.dbcp spring-boot will give you the newer (and IMHO better) tomcat connection pool (which despite the name can be used entirely on its own).
I will remodify your code in better approach.
Firstly no need of using new operator in your code as you are using Spring so you can use the powerful feature of Spring i.e Dependency Injection.
#RestController
public class DetailReportController
{ #Required
private JdbcTemplate jt;
//setter for the same
#RequestMapping(value="/report/detail", method=RequestMethod.GET)
public List<UFGroup> detailReport()
{
List<UFGroup> results = jt.query(
"select NID, SCode, SName from UFGroup",
new RowMapper<UFGroup>()
{
#Override
public UFGroup mapRow(ResultSet rs, int rowNum) throws SQLException
{
return new UFGroup(rs.getInt("NID"), rs.getString("SCode"),
rs.getString("SName"));
}
});
return results;
}
private static class UFGroup
{
public int nid;
public String scode;
public String sname;
public UFGroup(int nid, String scode, String sname)
{
this.nid = nid;
this.scode = scode;
this.sname = sname;
}
}
}
application-context.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="30"/>
<property name="maxWait" value="16000"/>
<property name="minIdle" value="0"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate;">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="detailReportController" class="your class">
<property name="jt" ref="jt"/>
</bean>
Another suggestion that you can move your code related to database in DAO classes,its very bad practice to have the same in Controller.Else if you want to stick to your approach use Properties class of java.util package
See here

Resources