spring-kafka 2.0.x kafka .11 and spring-boot 2.0.0.RELEASE compatibility issues: java.lang.NoSuchMethodError - spring-boot

When upgrading from spring-boot 2.0.0.Mx to 2.0.0.RELEASE it looks like there are incompatibilities between spring-boot, spring-kafka 2.0.x, and kafka .11. The compatibility issues are clearly defined between spring-kafka and the kafka version here. However when using the compatible versions mentioned and upgrading to spring-boot 2.0.0.RELEASE the following exception is thrown.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-12 10:48:34.501 ERROR 13141 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kafkaListenerContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory]: Factory method 'kafkaListenerContainerFactory' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: org.springframework.kafka.listener.config.ContainerProperties.setClientId(Ljava/lang/String;)V
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234)
at Server.main(Server.kt:19)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory]: Factory method 'kafkaListenerContainerFactory' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: org.springframework.kafka.listener.config.ContainerProperties.setClientId(Ljava/lang/String;)V
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 18 common frames omitted
Caused by: java.lang.BootstrapMethodError: java.lang.NoSuchMethodError: org.springframework.kafka.listener.config.ContainerProperties.setClientId(Ljava/lang/String;)V
at org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer.configureContainer(ConcurrentKafkaListenerContainerFactoryConfigurer.java:99)
at org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer.configure(ConcurrentKafkaListenerContainerFactoryConfigurer.java:80)
at org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration.kafkaListenerContainerFactory(KafkaAnnotationDrivenConfiguration.java:72)
at org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration$$EnhancerBySpringCGLIB$$b9d721e8.CGLIB$kafkaListenerContainerFactory$1(<generated>)
at org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration$$EnhancerBySpringCGLIB$$b9d721e8$$FastClassBySpringCGLIB$$25044a84.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
at org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration$$EnhancerBySpringCGLIB$$b9d721e8.kafkaListenerContainerFactory(<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)
... 19 common frames omitted
Caused by: java.lang.NoSuchMethodError: org.springframework.kafka.listener.config.ContainerProperties.setClientId(Ljava/lang/String;)V
at java.lang.invoke.MethodHandleNatives.resolve(Native Method)
at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:975)
at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1000)
at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1394)
at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(MethodHandles.java:1750)
at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:477)
... 32 common frames omitted
According to Artem Bilan in this random gitter thread, spring-boot 2 is only compatible with spring-kafka 2.1.x. I couldn't find any documentation stating this.
Given all of this these are my only options:
Upgrade to kafka 1.0 because spring-kafka 2.1 is only compatible with kafka 1.0.
Stick with an older version of spring-boot.
Configure kafka manually (I haven't proven this will work but would make sense).
Is there something in the works to allow compatibility between spring-boot 2 and older version of spring-kafka?

I do like this in POM to downgrade Spring Kafka:
<properties>
<spring-kafka.version>2.0.4.RELEASE</spring-kafka.version>
</properties>
Then I get the same NoSuchMethodError. From there I jumped to the ConcurrentKafkaListenerContainerFactoryConfigurer and decided to override it according KafkaAnnotationDrivenConfiguration:
#Bean
public ConcurrentKafkaListenerContainerFactoryConfigurer kafkaListenerContainerFactoryConfigurer(
KafkaProperties kafkaProperties,
ObjectProvider<RecordMessageConverter> messageConverterObjectProvider,
ObjectProvider<KafkaTemplate<Object, Object>> kafkaTemplateObjectProvider) {
RecordMessageConverter messageConverter = messageConverterObjectProvider.getIfUnique();
KafkaTemplate<Object, Object> kafkaTemplate = kafkaTemplateObjectProvider.getIfUnique();
return new ConcurrentKafkaListenerContainerFactoryConfigurer() {
#Override
public void configure(ConcurrentKafkaListenerContainerFactory<Object, Object> listenerFactory,
ConsumerFactory<Object, Object> consumerFactory) {
listenerFactory.setConsumerFactory(consumerFactory);
configureListenerFactory(listenerFactory);
configureContainer(listenerFactory.getContainerProperties());
}
private void configureListenerFactory(
ConcurrentKafkaListenerContainerFactory<Object, Object> factory) {
PropertyMapper map = PropertyMapper.get();
KafkaProperties.Listener properties = kafkaProperties.getListener();
map.from(properties::getConcurrency).whenNonNull().to(factory::setConcurrency);
map.from(() -> messageConverter).whenNonNull()
.to(factory::setMessageConverter);
map.from(() -> kafkaTemplate).whenNonNull().to(factory::setReplyTemplate);
map.from(properties::getType).whenEqualTo(KafkaProperties.Listener.Type.BATCH)
.toCall(() -> factory.setBatchListener(true));
}
private void configureContainer(ContainerProperties container) {
PropertyMapper map = PropertyMapper.get();
KafkaProperties.Listener properties = kafkaProperties.getListener();
map.from(properties::getAckMode).whenNonNull().to(container::setAckMode);
map.from(properties::getAckCount).whenNonNull().to(container::setAckCount);
map.from(properties::getAckTime).whenNonNull().as(Duration::toMillis)
.to(container::setAckTime);
map.from(properties::getPollTimeout).whenNonNull().as(Duration::toMillis)
.to(container::setPollTimeout);
map.from(properties::getNoPollThreshold).whenNonNull()
.to(container::setNoPollThreshold);
map.from(properties::getIdleEventInterval).whenNonNull().as(Duration::toMillis)
.to(container::setIdleEventInterval);
map.from(properties::getMonitorInterval).whenNonNull().as(Duration::getSeconds)
.as(Number::intValue).to(container::setMonitorInterval);
}
};
}
Right, that's mostly copy-paste, but at least I stop to get that exception and propagate as much properties as possible.

Related

After spring boot upgrade from 2.1.3 to 2.2.6, spring boot test fails to create MongoHealthContributorAutoConfiguration bean

Had spring boot test-cases with the below annotations, which were working on 2.1.3 version.
Test class snippet of annotations:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.MOCK)
#ContextConfiguration(classes = {...., MongoTemplate.class})
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, MongoDataAutoConfiguration.class})
#AutoConfigureMockMvc
However, after upgrading spring boot to 2.2.6, the test cases started failing with below error
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoHealthContributor' defined in class path resource [org/springframework/boot/actuate/autoconfigure/mongo/MongoHealthContributorAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributor]: Factory method 'mongoHealthContributor' threw exception; nested exception is java.lang.IllegalArgumentException: Beans must not be empty
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:620)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:608)
at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1242)
at org.springframework.boot.actuate.autoconfigure.health.HealthEndpointConfiguration.healthContributorRegistry(HealthEndpointConfiguration.java:78)
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)
... 78 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributor]: Factory method 'mongoHealthContributor' threw exception; nested exception is java.lang.IllegalArgumentException: Beans must not be empty
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
... 96 common frames omitted
Caused by: java.lang.IllegalArgumentException: Beans must not be empty
at org.springframework.util.Assert.notEmpty(Assert.java:549)
at org.springframework.boot.actuate.autoconfigure.health.AbstractCompositeHealthContributorConfiguration.createContributor(AbstractCompositeHealthContributorConfiguration.java:52)
at org.springframework.boot.actuate.autoconfigure.mongo.MongoHealthContributorAutoConfiguration.mongoHealthContributor(MongoHealthContributorAutoConfiguration.java:54)
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)
Also, the POM doesn't have any use of sticky versions for spring-data or spring-cloud which might be causing spring library inconsistencies.

spring boot data cassandra reactive JmxReporter problem

I updated my project to spring-boot Version 2.1.0.RELEASE.
Now i get the following error:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSession]: Factory method 'reactiveSession' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.lambda$instantiate$2(ConstructorResolver.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:614)
... 120 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:339)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.session(<generated>)
at org.springframework.data.cassandra.config.AbstractCassandraConfiguration.getRequiredSession(AbstractCassandraConfiguration.java:66)
at org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration.reactiveSession(AbstractReactiveCassandraConfiguration.java:47)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.CGLIB$reactiveSession$7(<generated>)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7$$FastClassBySpringCGLIB$$7973a63.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.reactiveSession(<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)
... 123 more
Caused by: java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at com.datastax.driver.core.Metrics.<init>(Metrics.java:146)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1501)
at com.datastax.driver.core.Cluster.init(Cluster.java:208)
at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:376)
at com.datastax.driver.core.Cluster.connect(Cluster.java:332)
at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.connect(CassandraCqlSessionFactoryBean.java:89)
at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.afterPropertiesSet(CassandraCqlSessionFactoryBean.java:82)
at org.springframework.data.cassandra.config.CassandraSessionFactoryBean.afterPropertiesSet(CassandraSessionFactoryBean.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.lambda$invokeInitMethods$5(AbstractAutowireCapableBeanFactory.java:1795)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1794)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
... 143 more
Caused by: java.lang.ClassNotFoundException: com.codahale.metrics.JmxReporter
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 155 more
Using the property introduced in this issue https://github.com/spring-projects/spring-boot/issues/14778 seems to have no effect to solve my issue.
How can i disable jmx for cassandra?
My current cassandra config looks like this:
#Configuration
#EnableReactiveCassandraRepositories({"repository"})
public class CassandraConfig extends AbstractReactiveCassandraConfiguration {
#Value("${cassandra.host}")
private String host;
#Override
protected String getKeyspaceName() {
return "keyspace";
}
#Override
public String[] getEntityBasePackages() {
return new String[]{"model"};
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override
public String getContactPoints() {
return host;
}
}
The spring.data.cassandra.jmx-enabled property is used when Spring Boot is auto-configuring a Cassandra Cluster bean. By extending AbstractReactiveCassandraConfiguration, you are switching off this auto-configuration in favour of the Cluster bean that's created by AbstractClusterConfiguration which is a super-class of AbstractReactiveCassandraConfiguration. As a result, the property has no effect.
There are two ways that you can fix your problem:
Remove your AbstractReactiveCassandraConfiguration sub-class and use the various spring.data.cassandra.* properties to configure things instead.
Override cluster on AbstractClusterConfiguration in CassandraConfig, call super.cluster() to get the CassandraClusterFactoryBean and then call setJmxReportingEnabled(false) on the factory bean before returning it.
Alternatively, if you are not using Dropwizard elsewhere in your application, you may be able to downgrade to an older version that is compatible with Cassandra's JMX reporting by overriding the dropwizard-metrics.version property in your pom.xml or build.gradle.
instead of overriding cluster as mentionned by Andy Wilkinson, you could alternatively override getMetricsEnabled so that always returns false.
#Override
protected boolean getMetricsEnabled() { return false; }
I tried the the answers here, I don't know how but error still persisted.
I read this from docs.datastax.com , where they talked about Moving JMX reporting in Metrics 4 to a separate module, metrics-jmx. Which they made clear that it might cause issues/errors.
To fix this, I just had to call this method .withoutJMXReporting() as in the below.
Cluster cluster = Cluster.builder()
.withoutJMXReporting()
.build();
You can follow quietly here
Including old version of library also fixes problem:
implementation("io.dropwizard.metrics:metrics-core:3.2.2")
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("spring.data.cassandra.contact-points"));
cluster.setPort(Integer.parseInt(environment.getProperty("spring.data.cassandra.port")));
cluster.setJmxReportingEnabled(false);
return cluster;
}
cluster.setJmxReportingEnabled(false) is the answer seems.

Spring Boot application fails after adding #EnableResourceServer

I trying to create a resource server that will authenticate every request by validating the access token in the header. Whenever I add #EnableResourceServer on my application class the application fails to run. Once I remove the annotation above the application runs again. The error says I have no implementation of JAXB-API on my classpath.
Here is the code of my application class:
package com.example.oauthimplicit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
#EnableWebSecurity
#EnableResourceServer
#SpringBootApplication
public class OauthImplicitApplication extends WebSecurityConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(OauthImplicitApplication.class, args);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/index.html", "/config").permitAll()
.anyRequest().authenticated();
}
}
Here is my build.gradle:
buildscript {
ext {
springBootVersion = '2.0.5.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web')
testImplementation('org.springframework.boot:spring-boot-starter-test')
implementation('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.security.oauth:spring-security-oauth2:2.3.3.RELEASE')
compile('javax.xml.bind:jaxb-api:2.3.0')
testImplementation('org.springframework.security:spring-security-test')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
When I run the application I get the following error:
2018-10-05 17:52:57.524 WARN 16921 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
2018-10-05 17:52:57.528 INFO 16921 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-10-05 17:52:57.574 INFO 16921 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-05 17:52:57.586 ERROR 16921 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:590) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at com.example.oauthimplicit.OauthImplicitApplication.main(OauthImplicitApplication.java:18) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
... 20 common frames omitted
Caused by: java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at org.springframework.security.oauth2.http.converter.jaxb.AbstractJaxbMessageConverter.<init>(AbstractJaxbMessageConverter.java:62) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.http.converter.jaxb.JaxbOAuth2ExceptionMessageConverter.<init>(JaxbOAuth2ExceptionMessageConverter.java:21) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.geDefaultMessageConverters(DefaultOAuth2ExceptionRenderer.java:117) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.<init>(DefaultOAuth2ExceptionRenderer.java:53) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.error.AbstractOAuth2SecurityExceptionHandler.<init>(AbstractOAuth2SecurityExceptionHandler.java:42) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint.<init>(OAuth2AuthenticationEntryPoint.java:36) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer.<init>(ResourceServerSecurityConfigurer.java:62) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration.configure(ResourceServerConfiguration.java:118) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:230) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:321) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:92) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$$EnhancerBySpringCGLIB$$3d845712.init(<generated>) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$383bd88c.CGLIB$springSecurityFilterChain$3(<generated>) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$383bd88c$$FastClassBySpringCGLIB$$6f7b245e.invoke(<generated>) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:365) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$383bd88c.springSecurityFilterChain(<generated>) ~[spring-security-config-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
... 21 common frames omitted
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:421) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662) ~[jaxb-api-2.3.0.jar:2.3.0]
at org.springframework.security.oauth2.http.converter.jaxb.AbstractJaxbMessageConverter.<init>(AbstractJaxbMessageConverter.java:59) ~[spring-security-oauth2-2.3.3.RELEASE.jar:na]
... 46 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499) ~[na:na]
at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155) ~[jaxb-api-2.3.0.jar:2.3.0]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276) ~[jaxb-api-2.3.0.jar:2.3.0]
... 50 common frames omitted
Process finished with exit code 1
I've just fixed the same issue: after visiting the dependency page of (a quite new version of) Spring Security OAuth2 AutoConfigure (https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure/2.1.0.RELEASE) I decided to put/refresh all JAXB API related dependencies:
// Java 11
runtime('com.sun.xml.bind:jaxb-core:2.3.0.1')
runtime('com.sun.xml.bind:jaxb-impl:2.3.1')
runtime('javax.xml.bind:jaxb-api:2.3.1')
runtime('org.javassist:javassist:3.23.1-GA')
Now it works fine, hope it helps.
If you use Java 9 or higher you need to add this VM options in your Tomcat configuration
--add-modules
java.xml.bind
I was following a Udemy course on CQRS and Event sourcing and the instructor create an OAuth 2.0 server but when i ran the auth server it kept failing with this error. i tried everything, the only thing that worked is adding
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.28.0-GA</version>
</dependency>
Without this i kept getting the exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.8.jar:5.3.8]
So thank you. I am totally new to spring boot and oauth 2.0 type implementation and i was trying to wrack my brains on it and knew it wasnt something that i did different from the instructor.. it somehow worked for him on an older version of spring and java 14 but i am on spring 2.5+ and java 16

How to make spring boot web app exit non-zero when failing injecting a bean

I have a bean in my app(based on Spring Boot 1.5.3) which takes time to be initialized due to loading lots of resources. While the initialization of that bean the web app already started to listen on port, the spring boot app still is running even if the initialization of that bean failed then thrown exception.
However the app still is running though the bean was failed to be injected.
Any way to exit the spring web app with error code if the bean was failed to be injected.
Below is the way how injectecting my bean,
#Component
#Slf4j
#RefreshScope
#Profile("!integTest")
public class NoteSpellChecker {
private Directory spellIndexDirectory;
private SpellChecker spellChecker;
public NoteSpellChecker(#Value("${app.spellcheck.indexPath:build/suggest}") String spellIndexPath,
#Value("${app.spellcheck.accuracy:0.5f}") float spellAccuracy,
#Value("${app.spellcheck.suggestDirectory:${spring.cloud.config.uri}/${spring.application.name}" +
"/${spring.profiles.active}/${spring.cloud.config.label:master}/spellcheck/note.txt},")
String[] spellSuggestDirectories,
OkHttpClient httpClient) throws IOException {
**here run some initialization task that takes some time**
}
There is another bean depending on NoteSpellChecker. See code snippet below,
#Configuration
#Slf4j
public class NoteDBConfig {
#Bean
public List<NoteRecognizer> noteRecognizers(NoteSpellChecker noteSpellChecker,
NoteDBRepository noteDBRepository) {
return noteDBRepository.findByEnabled(true).sorted((n1, n2) -> n1.getOrder() - n2.getOrder())
.map(note -> new NoteRecognizerImpl(note, noteSpellChecker))
.collect(Collectors.toList());
}
}
The spring boot application failed to be started due to the error of initialization of bean, but the JVM still is running without exiting. So the daemon app(which starts the spring boot app) does not aware of the fatal exception of my app.
Below is the out in console,
2017-04-28 17:36:54.483 ERROR [magiceye-server,,,] 32444 --- [
main] o.s.boot.SpringApplication : Application startup
failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'scopedTarget.noteSpellChecker' defined in
file
[/.../service/impl/NoteSpellChecker.class]:
Bean instantiation via constructor failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [service.impl.NoteSpellChecker]:
Constructor threw exception; nested exception is java.io.IOException
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at
org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:345)
at
org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:359)
at
org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:176)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
at
org.springframework.cloud.context.scope.refresh.RefreshScope.start(RefreshScope.java:121)
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.context.event.ApplicationListenerMethodAdapter.doInvoke(ApplicationListenerMethodAdapter.java:253)
at
org.springframework.context.event.ApplicationListenerMethodAdapter.processEvent(ApplicationListenerMethodAdapter.java:174)
at
org.springframework.context.event.ApplicationListenerMethodAdapter.onApplicationEvent(ApplicationListenerMethodAdapter.java:137)
at
org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at
org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at
org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
at
org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:337)
at
org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:882)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545)
at
org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at
BackendApplication.main(BackendApplication.java:21)
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate
[service.impl.NoteSpellChecker]: Constructor threw
exception; nested exception is java.io.IOException at
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
... 32 common frames omitted Caused by: java.io.IOException: null at
service.impl.NoteSpellChecker.(NoteSpellChecker.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 34 common frames omitted
I found that it was caused by a daemon thread started by a third party library.

Add another PropertyResourceConfigurer programatically with spring-boot

We're setting up an advanced/complex multimodule build with gradle, groovy and spring-boot.
In addition to using #EnableAutoConfiguration to automatically pick up application*.yml files, we would like to register a "custom" PropertyResourceConfigurer to handle common properties placed in a separate "config" module which can be reused across several spring- boot apps.
However, when adding the following in a #Configuration annotated class, startup fails with an exception
#Configuration
class CommonConfig {
#Autowired
Environment env;
#Bean (name = 'geit')
PropertyResourceConfigurer geitProperties() {
PropertyResourceConfigurer configurer = new PropertyPlaceholderConfigurer();
Resource[] resources = new Resource[env.activeProfiles.length];
println "Environment2 : ${env}"
env.activeProfiles.eachWithIndex() {
env, i -> resources[i] = new UrlResource(getURL(String.format("classpath:environment/%s.properties", env)))
}
configurer.setLocations(resources)
return configurer
}
}
the exception is
4fa8a851930816b4d09ecb1/springloaded-1.2.1.RELEASE.jar]
at org.codehaus.groovy.runtime.NullObject.getProperty(NullObject.java:57)
2014-11-04 14:13:56.975 ERROR 48941 --- [ main] o.s.boot.SpringApplication : Application startup failed
at org.codehaus.groovy.runtime.InvokerHelper.getProperty(InvokerHelper.java:168)
at org.codehaus.groovy.runtime.callsite.NullCallSite.getProperty(NullCallSite.java:44)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'geit' defined in class path resource [geit/config/CommonConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.beans.factory.config.PropertyResourceConfigurer geit.config.CommonConfig.geitProperties()] threw exception; nested exception is java.lang.NullPointerException: Cannot get property 'activeProfiles' on null object
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:601)
at geit.config.CommonConfig.geitProperties(CommonConfig.groovy:55)
at geit.config.CommonConfig$$EnhancerBySpringCGLIB$$c13414af.CGLIB$geitProperties$21(<generated>)
at geit.config.CommonConfig$$EnhancerBySpringCGLIB$$c13414af$$FastClassBySpringCGLIB$$e7b06e5c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1113)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFaat geit.config.CommonConfig$$EnhancerBySpringCGLIB$$c13414af.geitProperties(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
ry.java:1008)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
... 22 more
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:150)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:692)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:962)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:951)
at org.springframework.boot.SpringApplication$run.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at geit.AdminApplication.main(AdminApplication.groovy:19)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.beans.factory.config.PropertyResourceConfigurer geit.config.CommonConfig.geitProperties()] threw exception; nested exception is java.lang.NullPointerException: Cannot get property 'activeProfiles' on null object
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:590)
... 21 common frames omitted
Caused by: java.lang.NullPointerException: Cannot get property 'activeProfiles' on null object
at org.codehaus.groovy.runtime.NullObject.getProperty(NullObject.java:57)
at org.codehaus.groovy.runtime.InvokerHelper.getProperty(InvokerHelper.java:168)
at org.codehaus.groovy.runtime.callsite.NullCallSite.getProperty(NullCallSite.java:44)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at geit.config.CommonConfig.geitProperties(CommonConfig.groovy:55)
at geit.config.CommonConfig$$EnhancerBySpringCGLIB$$c13414af.CGLIB$geitProperties$21(<generated>)
at geit.config.CommonConfig$$EnhancerBySpringCGLIB$$c13414af$$FastClassBySpringCGLIB$$e7b06e5c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at geit.config.CommonConfig$$EnhancerBySpringCGLIB$$c13414af.geitProperties(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.iate(SimpleInstantiationStrategy.java:166)
... 22 common frames omitted
However, when adding the following to CommonConfig
#Bean
public String profileConfigBean() {
println "Environment : ${env}"
env.activeProfiles.each {
println it
}
'devprofilebean'
}
this correctly prints all active profiles.
Even adding an empty PropertyResourceConfigurer causes startup to fail
Found a working solution.
I added a class annotated with #PropertySource for each environment pluss one for default properties.
examples:
One for DEV
#Configuration
#Profile(Profiles.DEV)
#PropertySource("classpath:/environment/dev.properties")
class CommonDevConfig {
}
and the one for default
#Configuration
#PropertySource("classpath:/environment/default.properties")
class CommonConfig {
}

Resources