HikariCP with Spring boot autoconfiguration & Spring Data - spring-boot

I am trying to use spring boot(1.4.3.RELEASE) autoconfoguration. This is a multi module project.
parent project
|---pom.xml -> This is a parent pom.
|---repository(Spring Data)
|---pom.xml
|---src
|---web
|---pom.xml
|---src
My application.properties,
# Dialer Data Access
spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.pool-name=cc_dialer
spring.datasource.hikari.driver-class-name=com.mariadb.jdbc.Driver
spring.datasource.hikari.url=jdbc:mysql://localhost:3306/dialer
spring.datasource.hikari.username=root
spring.datasource.hikari.password=root
spring.datasource.hikari.type com.zaxxer.hikari.HikariDataSource
web module Application.java,
#SpringBootApplication(exclude = { VelocityAutoConfiguration.class }, scanBasePackages =
{ "com.test.dbrepo.repository" })
#EnableScheduling
public class DialerApplication {
Web pom.xml,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Repository application,
#SpringBootApplication(scanBasePackages = { "com.cc.dialer.dbrepo" })
public class DialerDBServiceApplication {
Repository pom.xml,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<!-- <version>2.5.1</version>-->
</dependency>
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<!-- <version>1.5.7</version>-->
</dependency>
I am trying to use Spring boot autoconfiguration, but getting the below error.
2017-01-17 14:57:59.903 [main] WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext - 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 (the profiles "dev" are currently active).
2017-01-17 14:57:59.905 [main] INFO o.a.catalina.core.StandardService - Stopping service Tomcat
2017-01-17 14:57:59.911 [main] WARN o.s.boot.SpringApplication - Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available)
2017-01-17 14:57:59.914 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter -
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE

You can use something like below in your property file configuration.
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=<user>
spring.datasource.password=<password>
spring.datasource.driver-class-name=<driver classname>
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=50
spring.datasource.hikari.idle-timeout=1000
spring.datasource.hikari.pool-name=blah

Related

Start Springboot without any Undertow Configuration

I have a project which mixes 2 dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-installed-adapter</artifactId>
<version>11.0.2</version>
</dependency>
I'm getting a transitiv dependency for Undertow, which comes from
keycloak-installed-adapter
As far as I understood, Undertow is used internally within the KeyCloak libraries.
I don't want my Springboot Application to start with Undertow, nor I want that anything related with Undertow gets configured at Springboot level.
I can't find to completely exclude any Undertow configuration for Springboot. Does anyone have an idea?
Update
I now have the following:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {EmbeddedUndertow.class})
public class SpringbootTest {
public static void main(String[] args) {
SpringApplication.run(SpringbootTest.class, args);
}
}
But i'm getting following exception when starting my service:
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory]: Factory method 'undertowEmbeddedServletContainerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: io/undertow/servlet/api/SessionPersistenceManager
Knowing that the EmbeddedUndertow Class lokks like:
#Configuration
#ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
#ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
public static class EmbeddedUndertow {
#Bean
public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
return new UndertowEmbeddedServletContainerFactory();
}
}
How would you ignore this calss from the scanning?

Spring looking for PostgreSql driver, but I'm using JTDS

Loading a spring cloud dataflow app fails with this log:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.postgresql.Driver
But configuration is:
spring.jpa.database=sybase
spring.datasource.url=jdbc:jtds:sybase://xxx:X000/xxxx;autoCommit=false;appName=dataflow
spring.datasource.username=xx
spring.datasource.password=xxx
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver
spring.datasource.hikari.driver-class-name=net.sourceforge.jtdatasource.jdbc.Driver
spring.datasource.hikari.pool-name=datasource-pool
spring.datasource.hikari.connection-timeout=3000
spring.datasource.hikari.maximum-pool-size=2
spring.datasource.hikari.minimum-idle=0
spring.datasource.hikari.connection-test-query=SELECT 1
spring.datasource.hikari.auto-commit=false
spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED
Dependency:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
PostgreSql is never specified.
Using spring boot 2.3.3
Update:
I think something in spring dataflow context is setting the driver, because it works if I create my own configuration class and don't use spring.datasource prefix:
#Configuration
public class DataSourceConfiguration {
#Bean
#Primary
#ConfigurationProperties("spring.ds")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("spring.ds.hikari")
public HikariDataSource sybaseDataSource() {
return dataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
}

Issue in creating Error creating bean with name 'objectMapper' defined in class path resource. in com.fasterxml.jackson.databind.ObjectMapper

I am facing issue in creating Error creating bean with name 'objectMapper' defined in class path resource. Only change I did was
updated pom.xml from
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>
<dependency>
to
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0.pr3</version>
</dependency>
<dependency>
I am getting following error while executing my project
019-10-16 14:04:50.065 [CorrelationId=] ERROR --- [ main] o.s.b.w.e.t.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException.
Message: Error creating bean with name 'org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration':
Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$$EnhancerBySpringCGLIB$$c58725a7]:
Constructor threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'resourceConfigCustomizer' defined in class path resource [org/springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration$JacksonResourceConfigCustomizer.class]:
Unsatisfied dependency expressed through method 'resourceConfigCustomizer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'objectMapper' defined in class path resource [com/test/test/marketing/banditsorchestrator/config/OwaspConfig.class]:
Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException:
Failed to introspect Class [com.fasterxml.jackson.databind.ObjectMapper] from ClassLoader [sun.misc.Launcher$AppClassLoader#18b4aac2]
Here is my code
#Configuration
public class OwaspConfig {
private ObjectMapper objectMapper;
#Bean
#Primary
public ObjectMapper objectMapper() {
JsonFactory factory = new JsonFactory();
factory.setCharacterEscapes(new OwaspCharacterEscapes());
objectMapper = new ObjectMapper(factory);
return new ObjectMapper(factory);
}
}
My issue was that although it was not specified in the pom, my application was using an older version of jackson-core (2.9.6). Added the following and it fixed my issue.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
I identified the outdated dependency using:
mvn dependency:tree
updated to 2.10.0 and problem resolved.

JedisConnectionFactory bean instantiation failure during application startup and throws java.lang.NullPointerException

I am using spring-boot-data, redis and jedis. I created jedisConnectionFactory and redisTemplate beans in a Configuration class. JedisConnectionFactory bean instantiation failure during application startup.
I use the latest libraries. This is the exception I get:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-
maven-plugin:2.2.0.BUILD-SNAPSHOT:run (default-cli) on project
Console: An exception occurred while running. null:
InvocationTargetException: Error creating bean with name
'consoleApplication': Unsatisfied dependency expressed through field
'bookRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'bookRepository': Cannot resolve reference
to bean 'redisKeyValueTemplate' while setting bean property
'keyValueOperations'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'redisKeyValueTemplate': Cannot resolve
reference to bean 'redisKeyValueAdapter' while setting constructor
argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'redisKeyValueAdapter': Cannot resolve
reference to bean 'redisTemplate' while setting constructor
argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'redisTemplate' defined in class path
resource [com/console/config/AppConfig.class]: Bean instantiation
via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.springframework.data.redis.core.RedisTemplate]:
Factory method 'redisTemplate' threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'jedisConnectionFactory' defined in class
path resource [com/console/config/AppConfig.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.springframework.data.redis.connection.jedis.JedisConnectionFactory]: Factory method 'jedisConnectionFactory' threw exception; nested exception is java.lang.NullPointerException -> [Help 1]
This is my pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<!-- <version>2.2.0.BUILD-SNAPSHOT</version> -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<!-- <version>3.0.1</version> -->
<!-- <type>jar</type> -->
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
This is my code:
#Configuration
public class AppConfig {
#Autowired
private RedisProperties redisProperties;
#Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisProperties.getHost(), redisProperties.getPort());redisStandaloneConfiguration.setPassword(redisProperties.getPassword());
JedisClientConfiguration.JedisClientConfigurationBuilder builder = JedisClientConfiguration.builder()
.connectTimeout(redisProperties.getTimeout())
.readTimeout(redisProperties.getJedis().getPool().getMaxWait());
if (redisProperties.isSsl())
builder.useSsl();
// Final JedisClientConfiguration
JedisClientConfiguration clientConfig = builder.build();//.usePooling().build();
return new JedisConnectionFactory(redisStandaloneConfiguration, clientConfig);
}
#Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
JedisConnectionFactory factory = jedisConnectionFactory();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
#Repository
public interface BookRepository extends CrudRepository<Book, Long> {
}
I expect the simple application to run without exception.
Any advice and insight is appreciated.
From reviewing JedisConnectionFactory code it seem like you can get such error only if one of the arguments to the Ctor is null.
public JedisConnectionFactory(RedisStandaloneConfiguration standaloneConfig, JedisClientConfiguration clientConfig) {
this(clientConfig);
Assert.notNull(standaloneConfig, "RedisStandaloneConfiguration must not be null!");
this.standaloneConfig = standaloneConfig;
}
I had the same problem. For me, the problem was the order in which the beans were created.
It's important that the jedisConnectionFactory bean is created before any of its dependencies. A way of telling Spring about this is by using the #DependsOn annotation. You could do something like this:
#SpringBootApplication
#DependsOn("jedisConnectionFactory")
public class Application extends SpringBootServletInitializer {
...
}
There are probably better ways of solving this! My suggestion is just a workaround.

Activating Avro message converter in Spring Cloud Dataflow

I am implementing a stream app on Spring Cloud Dataflow. I would like to use Avro based schema registry client for serialization and schema control.
My basic goal is to feed Source app with some external data, transform it to prepared avro-based schema and send it to a Sink app which will accept only this schema.
I would like to use the schema from external schema registry server, not the file version of the schema.
My code looks like:
#EnableBinding(Source.class)
#EnableSchemaRegistryClient
public class DisSampleSource {
private final DisSampleSourceProperties properties;
#Inject
public DisSampleSource(DisSampleSourceProperties properties) {
this.properties = properties;
}
#InboundChannelAdapter(Source.OUTPUT)
public String feed() throws IOException {
if (!Paths.get(properties.getPath()).toFile().exists()) {
throw new InvalidPathException(this.properties.getPath(),
"The file does not exists or is of not proper type.");
}
return new String(Files.readAllBytes(Paths.get(properties.getPath())), StandardCharsets.UTF_8);
}
}
POM:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-schema</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
During starting application I am passing property:
--spring.cloud.stream.bindings.output.contentType=application/foo.bar.v1+avro
At the moment, the application fails to start with following exception:
2017-02-13 16:25:30.430 WARN 2444 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'disSampleSource' defined in URL [jar:file:/D:/git/dis/sample/source/target/dis-sample-source-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/com/atsisa/bit/dis/sample/DisSampleSource.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.stream.config.ChannelBindingAutoConfiguration': Unsatisfied dependency expressed through field 'adapters'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.stream.messaging.Source': Invocation of init method failed; nested exception is org.springframework.cloud.stream.converter.ConversionException: No message converter is registered for application/foo.bar.v1+avro
2017-02-13 16:25:30.440 INFO 2444 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2017-02-13 16:25:30.480 INFO 2444 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-02-13 16:25:30.485 ERROR 2444 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'disSampleSource' defined in URL [jar:file:/D:/git/dis/sample/source/target/dis-sample-source-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/com/atsisa/bit/dis/sample/DisSampleSource.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.cloud.stream.config.ChannelBindingAutoConfiguration': Unsatisfied dependency expressed through field 'adapters'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cloud.stream.messaging.Source': Invocation of init method failed; nested exception is org.springframework.cloud.stream.converter.ConversionException: No message converter is registered for application/foo.bar.v1+avro
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.4.RELEASE.jar!/:4.3.4.RELEASE]
What am I doing wrong?
Avro is an optional dependency of Spring Cloud Stream Schema (as the intent is to support other formats in the future. In order to activate schema support, you should simply add
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.8.1</version>
</dependency>
to the project.

Resources