I'm working through the book Learning Spring Boot 2.0, Second Edition but using Spring Boot 2.5.6 so I suspect my issue might be related to me having to do things slightly with the different version.
I have this class:
#Component
public class InitDatabase {
#Bean
CommandLineRunner init(MongoOperations operations) {
return args -> {
operations.dropCollection(Image.class);
operations.insert(new Image("1", "learning-spring-boot-cover.jpg"));
operations.insert(new Image("2", "learning-spring-boot-2nd-edition-cover.jpg"));
operations.insert(new Image("3", "bazinga.png"));
operations.findAll(Image.class).forEach(image -> System.out.println(image.toString()));
};
}
}
When I run my application I get this error:
2021-11-25 12:26:42.870 DEBUG 71010 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : Application failed to start due to an exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.MongoOperations' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.12.jar:5.3.12]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.12.jar:5.3.12]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.12.jar:5.3.12]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:64) ~[spring-boot-2.5.6.jar:2.5.6]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.6.jar:2.5.6]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.6.jar:2.5.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.6.jar:2.5.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.6.jar:2.5.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.6.jar:2.5.6]
at com.paulcarron.learningspringboot.learningspringboot.LearningSpringBootApplication.main(LearningSpringBootApplication.java:12) ~[classes/:na]
2021-11-25 12:26:42.870 ERROR 71010 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Parameter 0 of method init in com.paulcarron.learningspringboot.learningspringboot.InitDatabase required a bean of type 'org.springframework.data.mongodb.core.MongoOperations' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.data.mongodb.core.MongoOperations' in your configuration.
This is my build.gradle:
plugins {
id 'org.springframework.boot' version '2.5.6'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.paulcarron.learningspringboot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.synchronoss.cloud:nio-multipart-parser:1.1.0'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'de.flapdoodle.embed:de.flapdoodle.embed.mongo'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'javax.persistence:javax.persistence-api:2.2'
}
test {
useJUnitPlatform()
}
My understanding is that I don't need to activate the with #EnableReactiveMongoRepositories as this is done automatically if Reactive MongoDB or Spring DataMongoDB 2.0+ are on the classpath.
Is there any obvious reason why this is not working?
I guess you're trying to init your database on the startup.
You can leverage the spring internal event mechanism.
When your application is ready, spring triggers the event ApplicationReadyEvent
You can listen to this event and init your collection:
#Component
public class DataInit implements ApplicationListener<ApplicationReadyEvent> {
private final MongoOperations operations;
public DataInit(MongoOperations operations) {
this.operations = operations;
}
#Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// init data
}
}
If you want to know more about spring events --> https://www.baeldung.com/spring-events
MongoOperations is the interface for interacting with Mongo in a blocking manner. ReactiveMongoOperations is the interface for interacting with Mongo in a reactive manner.
As you're using WebFlux (spring-boot-starter-webflux), it would appear that you want to build a reactive application. If so, you should replace your use of MongoOperations with ReactiveMongoOperations. The, if you want to build a blocking, Servlet-based web application would be to switch to spring-boot-starter-data-mongodb and spring-boot-starter-web.
I want to preload data and read that it was best to do this using a blocking API because when launching an application there is a risk of a thread lock issue when both the web container and my loader are starting up. The book I'm using is for an older veriosn of both Spring Boot and MongoDB.
It seems that the version of spring-boot-starter-data-mongodb-reactive that the book used contained MongoOperations but this was then split out. See this.
To use this I added implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' to my class path.
If there wasn't the issue of thread lock I could have used ReactiveMongoOperations instead.
Related
Good day everyone!
I have a spring boot web application for which I have added Load time weaving to be able to use AspectJ aspects for non-managed spring bean, but after that application failed to start. I have looked through many topics regarding the configuration of load time weaving for non-spring beans in the spring project but haven't met if anyone has faced the issue I currently have.
My configuration:
gradle dependencies:
dependencies {
compileOnly ("org.projectlombok:lombok:${lombokVersion}")
implementation("org.aspectj:aspectjweaver:1.9.9.1")
implementation ("org.mapstruct:mapstruct:${mapstructVersion}")
implementation("com.fasterxml.jackson.core:jackson-databind:2.14.0-rc1")
implementation ("mysql:mysql-connector-java:8.0.30")
implementation("org.opensearch.client:opensearch-java:2.1.0")
implementation("software.amazon.awssdk:apache-client:${awsSdkVersion}")
implementation("software.amazon.awssdk:regions:${awsSdkVersion}")
implementation("software.amazon.awssdk:auth:${awsSdkVersion}")
implementation("jakarta.json:jakarta.json-api:2.1.1")
implementation("commons-io:commons-io:2.11.0")
implementation ("org.springframework.boot:spring-boot-starter-web")
implementation ("org.springframework.boot:spring-boot-starter-data-jpa")
implementation ("org.springframework.boot:spring-boot-starter-security")
implementation ("org.springframework.boot:spring-boot-starter-validation")
implementation ("org.springframework.boot:spring-boot-starter-log4j2")
annotationProcessor ("org.projectlombok:lombok-mapstruct-binding:0.2.0")
annotationProcessor ("org.mapstruct:mapstruct-processor:${mapstructVersion}")
annotationProcessor ("org.projectlombok:lombok:${lombokVersion}")
testImplementation("org.testcontainers:mysql:1.17.5")
testImplementation ("org.springframework.boot:spring-boot-starter-test")
testImplementation("com.h2database:h2:2.1.214")
testCompileOnly("org.projectlombok:lombok:${lombokVersion}")
testAnnotationProcessor("org.projectlombok:lombok:${lombokVersion}")
}
The spring boot versions are:
springBootVersion=2.7.4
dependencyManagement=1.0.14.RELEASE
Main application class:
#SuppressWarnings({"checkstyle:FinalClass", "checkstyle:HideUtilityClassConstructor"})
#SpringBootApplication
#EnableGlobalMethodSecurity(securedEnabled = true)
#EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#EnableCaching
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(WhiteCoatApp.class, args);
}
}
Aspect:
#Aspect
public class DefaultViewsReturnHandler {
#Around("viewObjects()")
public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Do something");
return joinPoint.proceed();
}
#Pointcut("execution(* com.project.TestTest.getTestString(..))")
public void viewObjects() {}
}
Configuration of META-INF/aop.xml
<aspectj>
<aspects>
<aspect name="com.project.common.DefaultViewsReturnHandler"/>
</aspects>
<weaver options="-verbose -showWeaveInfo">
<include within="com.project..*"/>
</weaver>
</aspectj>
And the class itself i would like to apply the aspect to is the simple pojo
public class TestTest {
private String testString;
public String getTestString() {
return "myString";
}
}
I'm running the application with
-javaagent:libs/spring-instrument-6.0.0.jar
and java 17
But had the error:
[INFO ] 2022-11-17 18:49:51.009 [background-preinit] Version - HV000001: Hibernate Validator 6.2.5.Final
[INFO ] 2022-11-17 18:49:51.326 [main] RepositoryConfigurationDelegate - Bootstrapping Spring Data JPA repositories in DEFAULT mode.
[INFO ] 2022-11-17 18:49:51.359 [main] RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 29 ms. Found 2 JPA repository interfaces.
[ERROR] 2022-11-17 18:49:51.454 [main] SpringApplication - Application run failed
java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) accessible: module java.base does not "opens java.lang" to unnamed module #5dda768f
at java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354) ~[?:?]
at java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297) ~[?:?]
at java.lang.reflect.Method.checkCanSetAccessible(Method.java:199) ~[?:?]
at java.lang.reflect.Method.setAccessible(Method.java:193) ~[?:?]
at org.springframework.util.ReflectionUtils.makeAccessible(ReflectionUtils.java:577) ~[spring-core-5.3.23.jar:5.3.23]
at org.springframework.context.support.ContextTypeMatchClassLoader$ContextOverridingClassLoader.isEligibleForOverriding(ContextTypeMatchClassLoader.java:99) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.core.OverridingClassLoader.loadClass(OverridingClassLoader.java:87) ~[spring-core-5.3.23.jar:5.3.23]
at java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[?:?]
at org.springframework.core.OverridingClassLoader.loadClass(OverridingClassLoader.java:82) ~[spring-core-5.3.23.jar:5.3.23]
at org.springframework.context.support.ContextTypeMatchClassLoader.loadClass(ContextTypeMatchClassLoader.java:70) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1594) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1534) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:704) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:674) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1670) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:570) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:221) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:762) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:567) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.4.jar:2.7.4]
at com.piecestech.whitecoat.platform.WhiteCoatApp.main(WhiteCoatApp.java:20) ~[main/:?]
[WARN ] 2022-11-17 18:49:51.465 [main] SpringApplication - Unable to close ApplicationContext
java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.findLoadedClass(java.lang.String) accessible: module java.base does not "opens java.lang" to unnamed module #5dda768f
at java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354) ~[?:?]
at java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297) ~[?:?]
at java.lang.reflect.Method.checkCanSetAccessible(Method.java:199) ~[?:?]
at java.lang.reflect.Method.setAccessible(Method.java:193) ~[?:?]
at org.springframework.util.ReflectionUtils.makeAccessible(ReflectionUtils.java:577) ~[spring-core-5.3.23.jar:5.3.23]
at org.springframework.context.support.ContextTypeMatchClassLoader$ContextOverridingClassLoader.isEligibleForOverriding(ContextTypeMatchClassLoader.java:99) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.core.OverridingClassLoader.loadClass(OverridingClassLoader.java:87) ~[spring-core-5.3.23.jar:5.3.23]
at java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[?:?]
at org.springframework.core.OverridingClassLoader.loadClass(OverridingClassLoader.java:82) ~[spring-core-5.3.23.jar:5.3.23]
at org.springframework.context.support.ContextTypeMatchClassLoader.loadClass(ContextTypeMatchClassLoader.java:70) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1594) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1534) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:704) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:674) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1670) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:570) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:669) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:661) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1300) ~[spring-context-5.3.23.jar:5.3.23]
at org.springframework.boot.SpringApplication.getExitCodeFromMappedException(SpringApplication.java:867) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.getExitCodeFromException(SpringApplication.java:855) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.handleExitCode(SpringApplication.java:842) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:782) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:318) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.4.jar:2.7.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.4.jar:2.7.4]
at com.piecestech.whitecoat.platform.WhiteCoatApp.main(WhiteCoatApp.java:20) ~[main/:?]
Will appreciate any thoughts on this!
In the AspectJ release notes you can read the following:
Use LTW on Java 16+
Please note that if you want to use load-time weaving on Java 16+, the weaving agent collides with JEP 396 (Strongly Encapsulate JDK Internals by Default) and related subsequent JEPs. Therefore, you need to set the JVM parameter --add-opens java.base/java.lang=ALL-UNNAMED in order to enable aspect weaving. This is due to the fact that the weaver uses internal APIs for which we have not found an adequate replacement yet when defining classes in different classloaders.
I use this kafka configuration with spring cloud and spring boot 2.6.6:
#Configuration
#RefreshScope
public class KafkaProducerConfig {
#Bean(name = "nativeProducerFactory")
#Primary
#RefreshScope
public ProducerFactory<String, String> nativeProducerFactory() {
final Map<String, Object> properties = new HashMap<>();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return new DefaultKafkaProducerFactory<>(properties);
}
#Bean(name = "nativeKafkaTemplate")
public KafkaTemplate<String, String> nativeKafkaTemplate(
#Autowired final ProducerFactory<String, String> factory) {
return new KafkaTemplate<>(factory);
}
But when I start the project I get this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.kafka.core.ProducerFactory<java.lang.Object, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1799)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1355)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389)
at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.getIfUnique(DefaultListableBeanFactory.java:2072)
at org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration.<init>(KafkaAnnotationDrivenConfiguration.java:93)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301)
at com.atlas.psp.AtlasRouterApplication.main(AtlasRouterApplication.java:48)
21:45:59.271 [main] ERROR LoggingFailureAnalysisReporter[report:40] -
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method kafkaTemplate in org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration required a bean of type 'org.springframework.kafka.core.ProducerFactory' that could not be found.
The following candidates were found but could not be injected:
- User-defined bean method 'nativeProducerFactory' in 'KafkaProducerConfig'
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.kafka.core.ProducerFactory' in your configuration.
Do you know how I can fix this issue?
When I remove #RefreshScope from the bean it's working fine. Do you know how I can fix this issue?
P.S Looks like adding #RefreshScope also like this solves the error:
#Bean(name = "nativeKafkaTemplate")
#RefreshScope
public KafkaTemplate<String, String> nativeKafkaTemplate(
#Autowired final ProducerFactory<String, String> factory) {
return new KafkaTemplate<>(factory);
}
But I think that is incorrect. Any idea what should be the correct way to fix this?
The issue is related to the #RefreshScope on the #Configuration class. Better define #RefreshScope for the specific #Bean.
Accrding to Spring Cloud Context - Refresh Scope
#RefreshScope works (technically) on an #Configuration class, but it
might lead to surprising behavior. For example, it does not mean that
all the #Beans defined in that class are themselves in #RefreshScope.
Specifically, anything that depends on those beans cannot rely on them
being updated when a refresh is initiated, unless it is itself in
#RefreshScope. In that case, it is rebuilt on a refresh and its
dependencies are re-injected. At that point, they are re-initialized
from the refreshed #Configuration)
Tha's why it's working when you move it to the #Bean.
I am unable to test my controller class by mocking UserService.save() method to return a dummy User object.
Keep getting the following exception
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.core.userdetails.UserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.1.jar:2.6.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.1.jar:2.6.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.1.jar:2.6.1]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:121) ~[spring-boot-test-2.6.1.jar:2.6.1]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.3.13.jar:5.3.13]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-5.3.13.jar:5.3.13]
... 67 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.core.userdetails.UserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656) ~[spring-beans-5.3.13.jar:5.3.13]
... 86 common frames omitted
I checked my service class but all seems fine there. Moreover the code runs perfectly fine when I run it as a spring boot application.
Can someone help me understand why Spring IOC is unable to register the bean when running the junit test.
#SpringBootTest
public class TestUserController {
#Autowired
private MockMvc mockMvc;
#MockBean
UserService userService;
#Autowired
private UserController controller;
#Test
public void contextLoads() throws Exception {
assertThat(controller).isNotNull();
}
#Test
public void checkUserRegistrationEndpoint() throws Exception {
ObjectMapper mapper = new ObjectMapper();
UserDto userDto = new UserDto();
User user = new User();
Mockito.when(userService.save(userDto)).thenReturn(user);......
#Service
public interface UserService {
User save(UserDto user);
List<User> findAll();
User findOne(String username);
AuthToken refreshToken(String refreshToken);
}
#Service
public class UserServiceImpl implements UserDetailsService, UserService {
protected final Log logger = LogFactory.getLog(getClass());......
NOTE: I have configured this application for JWT based authentication.
You are autowiring MockMvc, so you need to provide the #AutoConfigureMockMvc annotation on your test class, which will tell Spring to inject this class for you (as stated in the docs):
#SpringBootTest
#AutoConfigureMockMvc
public class TestUserController {
....
}
The same annotation includes registration of various Spring auto-configuration classes as stated in this answer, among others the MockMvcSecurityAutoConfiguration, which offers auto-configuration for Spring Security for tests (as stated in the docs).
If this does not solve your problem with the missing bean dependency, you can try to inject it with #MockBean too:
#MockBean
UserDetailsService userDetailsService;
I am trying to upgrade our gradle spring boot application from 2.1.4.RELEASE to 2.5.0, it builds fine, but when I am trying to do a gradle bootrun, it is giving the following error below.
Can anybody help what dependency I need to upgrade along with Springboot version
Here is the build.gradle
project.ext.set("buildInfo.build.number", version)
buildscript {
ext {
springBootVersion = '2.5.0'
}
repositories {
mavenCentral()
jcenter()
maven {
url "https://artifactory.build.ge.com/ARJLY"
credentials {
username = "${artifactory_user}"
password = "${artifactory_password}"
}
name = "oa-publish-repo"
}
maven { url "https://repo.spring.io/plugins-release" }
maven { url "https://repo.spring.io/libs-release" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
//docker
classpath('se.transmode.gradle:gradle-docker:1.2')
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'maven-publish'
apply plugin: 'distribution'
apply plugin: 'application'
apply plugin: 'docker'
apply plugin: 'jacoco'
group = 'com.ge.digital.oa.moa'
archivesBaseName = 'moa-svc'
sourceCompatibility = 1.8
wrapper {
gradleVersion = '5.1'
}
//dependencyManagement {
// imports {
// mavenBom 'org.springframework.cloud:spring-cloud-aws:2.0.1.RELEASE'
// }
//}
repositories {
mavenCentral()
add buildscript.repositories.getByName("oa-publish-repo")
maven { url "https://repo.spring.io/libs-release" }
}
mainClassName = "com.ge.digital.oa.moa.MoaApplication"
eclipse {
classpath {
downloadSources = true
}
}
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
}
sourceSets {
generated
}
sourceSets.generated.java.srcDirs = ['src/main/generated']
configurations{
querydslapt
}
dependencies {
implementation('com.ge.digital.oa.common:oa-common:3.0.0') {
exclude module: 'slf4j-log4j12'
exclude group: 'io.micrometer', module: 'micrometer-core'
}
//implementation('org.springframework.security:spring-security-oauth2-client')
implementation('org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.9.RELEASE')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.springframework.boot:spring-boot-starter-webflux')
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.apache.commons:commons-lang3');
implementation('commons-fileupload:commons-fileupload:1.4')
implementation("com.h2database:h2")
implementation('org.postgresql:postgresql:42.2.5')
compileOnly('org.projectlombok:lombok')
annotationProcessor('org.projectlombok:lombok')
implementation('org.springframework.boot:spring-boot-starter-actuator')
implementation("org.flywaydb:flyway-core")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.junit.jupiter:junit-jupiter-engine")
developmentOnly("org.springframework.boot:spring-boot-devtools")
implementation('com.opencsv:opencsv:4.4')
compile ("org.apache.commons:commons-csv:1.5")
compile("com.querydsl:querydsl-core:4.2.1")
compile("com.querydsl:querydsl-jpa:4.2.1")
compile("com.querydsl:querydsl-apt:4.2.1:jpa")
annotationProcessor(
"javax.persistence:javax.persistence-api",
"com.querydsl:querydsl-apt:4.2.1:jpa"
)
implementation("org.hibernate:hibernate-envers:5.3.9.Final")
// https://mvnrepository.com/artifact/com.vladmihalcea/hibernate-types-52
implementation group: 'com.vladmihalcea', name: 'hibernate-types-52', version: '2.10.3'
//OSS Scan fix
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.5.0'
}
//querydsl {
// querydsl.excludedClasses = ""
//}
compileJava {
options.compilerArgs << "-s"
options.compilerArgs << "$projectDir/src/main/generated"
doFirst {
// make sure that directory exists
file(new File(projectDir, "/src/main/generated")).mkdirs()
}
}
clean.doLast {
// clean-up directory when necessary
file(new File(projectDir, "/src/main/generated")).deleteDir()
}
sourceSets {
generated {
java {
srcDir "$projectDir/src/main/generated"
}
}
}
test {
useJUnitPlatform {
//includeTags 'fast', 'smoke & feature-a'
// excludeTags 'slow', 'ci'
//includeEngines 'junit-jupiter'
// excludeEngines 'junit-vintage'
}
testLogging {
events "passed", "skipped", "failed"
}
}
jar {
baseName = 'moa-application'
}
And below is the Error I am getting when I try to run gradle bootrun
$ gradle bootrun
> Task :bootRun
2021-08-12 10:39:08.127 INFO 16268 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-08-12 10:39:08.608 INFO 16268 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$723d7fce] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-08-12 10:39:08.640 WARN 16268 --- [ restartedMain] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurationPropertiesBeans' defined in org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans]: Factory method 'configurationPropertiesBeans' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
2021-08-12 10:39:08.859 WARN 16268 --- [kground-preinit] o.s.h.c.j.Jackson2ObjectMapperBuilder : For Jackson Kotlin classes support please add "com.fasterxml.jackson.module:jackson-module-kotlin" to the classpath
2021-08-12 10:39:08.874 INFO 16268 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-08-12 10:39:08.931 ERROR 16268 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurationPropertiesBeans' defined in org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans]: Factory method 'configurationPropertiesBeans' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:486) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:270) ~[spring-context-5.3.7.jar:5.3.7]
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:762) ~[spring-context-5.3.7.jar:5.3.7]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:567) ~[spring-context-5.3.7.jar:5.3.7]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:438) ~[spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:337) ~[spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:144) [spring-boot-2.5.0.jar:2.5.0]
at org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:197) [spring-cloud-context-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:104) [spring-cloud-context-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.cloud.bootstrap.BootstrapApplicationListener.onApplicationEvent(BootstrapApplicationListener.java:70) [spring-cloud-context-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) [spring-context-5.3.7.jar:5.3.7]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) [spring-context-5.3.7.jar:5.3.7]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) [spring-context-5.3.7.jar:5.3.7]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131) [spring-context-5.3.7.jar:5.3.7]
at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:82) [spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:63) [spring-boot-2.5.0.jar:2.5.0]
at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_251]
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:117) [spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:111) [spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:62) [spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:373) ~[spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:331) ~[spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1336) ~[spring-boot-2.5.0.jar:2.5.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1325) ~[spring-boot-2.5.0.jar:2.5.0]
at com.ge.digital.oa.moa.MoaApplication.main(MoaApplication.java:16) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_251]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.5.0.jar:2.5.0]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.context.properties.ConfigurationPropertiesBeans]: Factory method 'configurationPropertiesBeans' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.7.jar:5.3.7]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.7.jar:5.3.7]
... 39 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration.configurationPropertiesBeans(ConfigurationPropertiesRebinderAutoConfiguration.java:51) ~[spring-cloud-context-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$723d7fce.CGLIB$configurationPropertiesBeans$3(<generated>) ~[spring-cloud-context-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$723d7fce$$FastClassBySpringCGLIB$$150902fe.invoke(<generated>) ~[spring-cloud-context-2.0.0.RELEASE.jar:2.0.0.RELEASE]
Seems it has been removed with the suggestion that org.springframework.boot.context.properties.ConfigurationPropertiesBean be used instead, as of June 23, 2020.
I have updated the following spring dependencies in my project pom.xml
From:
<spring.version>5.3.6</spring.version>
<spring.security.version>5.4.4</spring.security.version>
<spring.boot.version>2.3.10.RELEASE</spring.boot.version>
To:
<spring.version>5.3.8</spring.version>
<spring.security.version>5.5.1</spring.security.version
<spring.boot.version>2.5.2</spring.boot.version>
I was able to build my project successfully whereas, when I tried to start my application, I see the following error and my application fails to start at all.
Can any one help me with the resolution.
Caused by: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException: warning can't determine superclass of missing type org.springframework.boot.validation.beanvalidation.MethodValidationExcludeFilter$$Lambda$819.0x000000080096f440
[Xlint:cantFindType]
at org.aspectj.weaver.reflect.ReflectionWorld$ExceptionBasedMessageHandler.handleMessage(ReflectionWorld.java:217) ~[aspectjweaver-1.9.7.jar!/:?]
at org.aspectj.weaver.Lint$Kind.signal(Lint.java:339) ~[aspectjweaver-1.9.7.jar!/:1.9.7]
at org.aspectj.weaver.MissingResolvedTypeWithKnownSignature.raiseCantFindType(MissingResolvedTypeWithKnownSignature.java:237) ~[aspectjweaver-1.9.7.jar!/:1.9.7]
at org.aspectj.weaver.MissingResolvedTypeWithKnownSignature.getSuperclass(MissingResolvedTypeWithKnownSignature.java:98) ~[aspectjweaver-1.9.7.jar!/:1.9.7]
at org.aspectj.weaver.JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember(JoinPointSignatureIterator.java:95) ~[aspectjweaver-1.9.7.jar!/:1.9.7]
at org.aspectj.weaver.JoinPointSignatureIterator.<init>(JoinPointSignatureIterator.java:49) ~[aspectjweaver-1.9.7.jar!/:1.9.7]
at org.aspectj.weaver.MemberImpl.getJoinPointSignatures(MemberImpl.java:515) ~[aspectjweaver-1.9.7.jar!/:1.9.7]
at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:316) ~[aspectjweaver-1.9.7.jar!/:?]
at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:202) ~[aspectjweaver-1.9.7.jar!/:?]
at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137) ~[aspectjweaver-1.9.7.jar!/:?]
at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.getShadowMatch(PointcutExpressionImpl.java:319) ~[aspectjweaver-1.9.7.jar!/:?]
at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.matchesExecution(PointcutExpressionImpl.java:129) ~[aspectjweaver-1.9.7.jar!/:?]
at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.matchesMethodExecution(PointcutExpressionImpl.java:110) ~[aspectjweaver-1.9.7.jar!/:?]
at org.springframework.security.config.method.ProtectPointcutPostProcessor.attemptMatch(ProtectPointcutPostProcessor.java:148) ~[spring-security-config-5.5.1.jar!/:5.5.1]
at org.springframework.security.config.method.ProtectPointcutPostProcessor.postProcessBeforeInitialization(ProtectPointcutPostProcessor.java:125) ~[spring-security-config-5.5.1.jar!/:5.5.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:422) ~[spring-beans-5.3.8.jar!/:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.3.8.jar!/:5.3.8]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) ~[spring-beans-5.3.8.jar!/:5.3.8]
... 23 more
Warning!
This is not Production Grade solution but this may be considered as starting point for further investigation.
Background
We have quite legacy (~10yo) application and we currently run into same issue during Spring Boot upgrade from 2.3.9 to 2.4.0 (Full stack below).
It seems to me that problem is related to three issues:
ProtectPointcutPostProcessor - from spring security
MethodValidationPostProcessor - which lack of disables the error
change in Spring Boot 2.4.0 - which is described below
Possible cause description
In Spring Boot 2.4.0 new Bean has been introduced in EnableConfigurationPropertiesRegistrar:
static void registerMethodValidationExcludeFilter(BeanDefinitionRegistry registry) {
if (!registry.containsBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.genericBeanDefinition(MethodValidationExcludeFilter.class,
() -> MethodValidationExcludeFilter.byAnnotation(ConfigurationProperties.class))
.setRole(BeanDefinition.ROLE_INFRASTRUCTURE).getBeanDefinition();
registry.registerBeanDefinition(METHOD_VALIDATION_EXCLUDE_FILTER_BEAN_NAME, definition);
}
}
This bean is generated with MethodValidationExcludeFilter.byAnnotation as Lambda:
static MethodValidationExcludeFilter byAnnotation(Class<? extends Annotation> annotationType,
SearchStrategy searchStrategy) {
return (type) -> MergedAnnotations.from(type, SearchStrategy.SUPERCLASS).isPresent(annotationType);
}
Because of being Lambda it has no parent class and fails miserably on bean creation post processing.
(Very) hacky solution
Luckily EnableConfigurationPropertiesRegistrar.registerMethodValidationExcludeFilter contains if statement which checks if bean has not been created. So we may create this bean manually instead:
#Bean("org.springframework.boot.context.properties.EnableConfigurationPropertiesRegistrar.methodValidationExcludeFilter")
public MethodValidationExcludeFilter mockMethodValidationExcludeFilter() {
return new MethodValidationExcludeFilter() {
#Override
public boolean isExcluded( Class< ? > type ) {
return MethodValidationExcludeFilter.byAnnotation( ConfigurationProperties.class).isExcluded( type );
}
};
}
Or even as:
#Bean("org.springframework.boot.context.properties.EnableConfigurationPropertiesRegistrar.methodValidationExcludeFilter")
public String mockMethodValidationExcludeFilter() {
return "mockMethodValidationExcludeFilter";
}
But this seems to me as very dirty hack and not suitable for production usage.
Theoretically disabling linting error cantFindType could also save the day as doing it on debug has allowed application to run but
we have not achieved proper configuration to disable it
this seems as dirty hack as well and should be considered as last resort and not proper solution
Logs
Full error stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.context.properties.EnableConfigurationPropertiesRegistrar.methodValidationExcludeFilter' defined in class path resource [com/source/etf/common/aop/AopConfig.class]: Initialization of bean failed; nested exception is org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException: warning can't determine superclass of missing type com.source.etf.common.aop.AopConfig$$Lambda$751.0x00000008008fec40
[Xlint:cantFindType]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:617) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.1.jar:5.3.1]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.0.jar:2.4.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.0.jar:2.4.0]
at com.source.etf.EtfmApplication.main(EtfmApplication.java:56) ~[main/:na]
Caused by: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException: warning can't determine superclass of missing type com.source.etf.common.aop.AopConfig$$Lambda$751.0x00000008008fec40
[Xlint:cantFindType]
at org.aspectj.weaver.reflect.ReflectionWorld$ExceptionBasedMessageHandler.handleMessage(ReflectionWorld.java:219) ~[aspectjweaver-1.9.6.jar:na]
at org.aspectj.weaver.Lint$Kind.signal(Lint.java:340) ~[aspectjweaver-1.9.6.jar:1.9.6]
at org.aspectj.weaver.MissingResolvedTypeWithKnownSignature.raiseCantFindType(MissingResolvedTypeWithKnownSignature.java:237) ~[aspectjweaver-1.9.6.jar:1.9.6]
at org.aspectj.weaver.MissingResolvedTypeWithKnownSignature.getSuperclass(MissingResolvedTypeWithKnownSignature.java:98) ~[aspectjweaver-1.9.6.jar:1.9.6]
at org.aspectj.weaver.JoinPointSignatureIterator.addSignaturesUpToFirstDefiningMember(JoinPointSignatureIterator.java:95) ~[aspectjweaver-1.9.6.jar:1.9.6]
at org.aspectj.weaver.JoinPointSignatureIterator.<init>(JoinPointSignatureIterator.java:49) ~[aspectjweaver-1.9.6.jar:1.9.6]
at org.aspectj.weaver.MemberImpl.getJoinPointSignatures(MemberImpl.java:515) ~[aspectjweaver-1.9.6.jar:1.9.6]
at org.aspectj.weaver.patterns.SignaturePattern.matches(SignaturePattern.java:319) ~[aspectjweaver-1.9.6.jar:na]
at org.aspectj.weaver.patterns.KindedPointcut.matchInternal(KindedPointcut.java:202) ~[aspectjweaver-1.9.6.jar:na]
at org.aspectj.weaver.patterns.Pointcut.match(Pointcut.java:137) ~[aspectjweaver-1.9.6.jar:na]
at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.getShadowMatch(PointcutExpressionImpl.java:319) ~[aspectjweaver-1.9.6.jar:na]
at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.matchesExecution(PointcutExpressionImpl.java:129) ~[aspectjweaver-1.9.6.jar:na]
at org.aspectj.weaver.internal.tools.PointcutExpressionImpl.matchesMethodExecution(PointcutExpressionImpl.java:110) ~[aspectjweaver-1.9.6.jar:na]
at org.springframework.security.config.method.ProtectPointcutPostProcessor.attemptMatch(ProtectPointcutPostProcessor.java:148) ~[spring-security-config-5.4.5.jar:5.4.5]
at org.springframework.security.config.method.ProtectPointcutPostProcessor.postProcessBeforeInitialization(ProtectPointcutPostProcessor.java:125) ~[spring-security-config-5.4.5.jar:5.4.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:429) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1780) ~[spring-beans-5.3.1.jar:5.3.1]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:609) ~[spring-beans-5.3.1.jar:5.3.1]
... 16 common frames omitted
Process finished with exit code 1