Spring Boot #Autowired custom application.properties - spring

i am trying to get my custon application.properties fields working within a kotlin spring boot application.
My Current Setup:
ApplicationProperties.kt:
#Configuration
#ConfigurationProperties("mt")
class ApplicationProperties {
var initDatabase: Boolean? = null
val kafka = Kafka()
class Kafka {
lateinit var host: String
lateinit var port: String
}
}
application.properties:
mt.kafka.host=localhost
mt.kafka.port=9092
mt.init-database=true
And a class where i want to use my application:
InitApp.kt
#Component
#EnableTransactionManagement
#EnableConfigurationProperties(ApplicationProperties::class)
class InitApp {
#Autowired
lateinit var conf: ApplicationProperties
#Bean
fun createKafkaConsumer() {
log.info("${conf.kafka.host}")
}
}
Sadly this doesn't work because i get a:
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property conf has not been initialized
I followed this "guide" Bootiful Kotlin by Sébastien Deleuze and Josh Long # Spring I/O 2018 and i am using these versions:
kotlinVersion = '1.2.51'
springBootVersion = '2.0.5.RELEASE'
apply plugin: 'kotlin-kapt' is in my build.gradle, but this should not mess with the #Autowired since, as far as i understood, it is for autocompletion in my application.properties.
Update 1:
I had a look at: Building web applications with Spring Boot and Kotlin and added the #EnableConfigurationProperties at Application level. This didn't work either
Update 2:
Full stacktrace:
2018-10-10 16:17:53.058 ERROR 23619 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'producerFactory' defined in class path resource [de/mikatiming/de/test/InitApp.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.kafka.core.ProducerFactory]: Factory method 'producerFactory' threw exception; nested exception is kotlin.UninitializedPropertyAccessException: lateinit property applicationProperties has not been initialized
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.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 de.mikatiming.de.test.TestApplicationKt.main(TestApplication.kt:15) [main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_172]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_172]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_172]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.5.RELEASE.jar:2.0.5.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.kafka.core.ProducerFactory]: Factory method 'producerFactory' threw exception; nested exception is kotlin.UninitializedPropertyAccessException: lateinit property applicationProperties has not been initialized
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]
... 23 common frames omitted
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property applicationProperties has not been initialized
at de.mikatiming.de.test.InitApp.getApplicationProperties(InitApp.kt:36) ~[main/:na]
at de.mikatiming.de.test.InitApp.producerFactory(InitApp.kt:58) ~[main/:na]
at de.mikatiming.de.test.InitApp$$EnhancerBySpringCGLIB$$c3b698bb.CGLIB$producerFactory$10(<generated>) ~[main/:na]
at de.mikatiming.de.test.InitApp$$EnhancerBySpringCGLIB$$c3b698bb$$FastClassBySpringCGLIB$$b315799f.invoke(<generated>) ~[main/:na]
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 de.mikatiming.de.test.InitApp$$EnhancerBySpringCGLIB$$c3b698bb.producerFactory(<generated>) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_172]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_172]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_172]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
... 24 common frames omitted
Update 3:
I just found out that when i remove a specific bean from my InitApp:
#Bean
fun placeHolderConfigurer(): PropertySourcesPlaceholderConfigurer {
return PropertySourcesPlaceholderConfigurer()
}
i get an other error message:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'de.mikatiming.messageengine.configuration.ApplicationProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
So it looks like it is an issue with this bean!

I managed to get it working:
Annotations
#Service
#Configuration
#EnableConfigurationProperties
#EnableTransactionManagement
class AppConfig {
ApplicationProperties:
#ConfigurationProperties("mt")
class ApplicationProperties {
ApplicationClass:
#SpringBootApplication
#EnableConfigurationProperties(ApplicationProperties::class)
abstract class MessageengineApplication
Beans
i needed to remove the following Bean from AppConfig:
#Bean
fun placeHolderConfigurer(): PropertySourcesPlaceholderConfigurer {
return PropertySourcesPlaceholderConfigurer()
}

This is ought to work:
#Component
#EnableTransactionManagement
#Configuration
#EnableConfigurationProperties(ApplicationProperties::class)
class InitApp {
#Autowired
lateinit var conf: ApplicationProperties
// ...
}
#ConfigurationProperties("mt")
class ApplicationProperties {
var initDatabase: Boolean? = null
val kafka = Kafka()
class Kafka {
lateinit var host: String
lateinit var port: String
}
}
Note that you need to put #Configuration on InitApp, not on ApplicationProperties.
I also have these in my build.gradle:
apply plugin: 'kotlin-spring'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
depencencies {
compile "org.springframework.boot:spring-boot-starter-web"
compileOnly "org.springframework.boot:spring-boot-configuration-processor"
}
dependencyManagement {
imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") }
}
You need the "org.springframework.boot:spring-boot-configuration-processor" dependency in place in order for this whole thing to work.

#EnableConfigurationProperties is usually put on classes marked with #Configuration annotation.
In the code snippet class InitApp should be marked as a #Configuration and then you can (I don't know Kotlin, so I'll provide a java equivalent):
#Configuration
#EnableTransactionManagement
#EnableConfigurationProperties(ApplicationProperties.class)
public class InitApp {
#Bean
public <<BeanThatYouNeed>> kafkaConsumer(ApplicationProperties props) {
log.info(props.getKafka().getHost());
}
}

you dont need those #Configuration, #ConfigurationProperties("mt") in the header of class ApplicationProperties
you can use #Value annotation to directly get the props from application.properties file
`
#Component
#EnableTransactionManagement
class InitApp {
#Autowired
lateinit var conf: ApplicationProperties
#Bean
fun createKafkaConsumer(#Value("${mt.kafka.host}") String host,
#Value("${mt.kafka.host}") String port) {
//you have host, port now
}
}
`

Related

Gradle build failed - Spring boot project with lombok

Cannot build Spring-boot project in Gradle. I get the following error (stack):
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:106)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appointmentController' defined in file [C:\Users\triin\Desktop\ValiIT\FinalProject\trikad_uus\build\classes\java\main\ee\bcs\valiit\trikad\controller\AppointmentController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appointmentService' defined in file [C:\Users\triin\Desktop\ValiIT\FinalProject\trikad_uus\build\classes\java\main\ee\bcs\valiit\trikad\service\AppointmentService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ee.bcs.valiit.trikad.data.AppointmentsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1267)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1124)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 49 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appointmentService' defined in file [C:\Users\triin\Desktop\ValiIT\FinalProject\trikad_uus\build\classes\java\main\ee\bcs\valiit\trikad\service\AppointmentService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ee.bcs.valiit.trikad.data.AppointmentsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1267)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1124)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724)
... 67 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ee.bcs.valiit.trikad.data.AppointmentsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) ...
The main problem seems to be in the file AppointmentController which is as follows:
package ee.bcs.valiit.trikad.controller;
import ee.bcs.valiit.trikad.data.Appointments;
import ee.bcs.valiit.trikad.service.AppointmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
#RestController
#RequestMapping(value = "/app")
#Slf4j
public class AppointmentController {
#Autowired
private AppointmentService appointmentService;
#PostMapping("/add")
private void add(#RequestParam String event_name, #RequestParam Date time, #RequestParam String description) {
Appointments app = new Appointments();
app.setEventname(event_name);
app.setTime(time);
app.setDescription(description);
appointmentService.add(app);
}
#PostMapping(value = "/delete/{id}", produces="application/json")
private void delete(#PathVariable Long id) {
Appointments app = appointmentService.get(id);
appointmentService.delete(app);
}
}
The file AppointmentService, that the controller uses is the following:
package ee.bcs.valiit.trikad.service;
import ee.bcs.valiit.trikad.data.Appointments;
import ee.bcs.valiit.trikad.data.AppointmentsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
public class AppointmentService {
#Autowired
private AppointmentsRepository appointmentsRepository;
public List<Appointments> list() {
return appointmentsRepository.findAll();
}
public Appointments get(Long id) {
return appointmentsRepository.getOne(id);
}
public List<Appointments> findByUserId(Long id) {
return appointmentsRepository.findByUserId(id);
}
#Transactional
public void delete(Appointments appointment) {
appointmentsRepository.delete(appointment);
}
#Transactional
public void add(Appointments appointment) {
appointmentsRepository.save(appointment);
}
}
And the repository that the service uses is a simple interface:
package ee.bcs.valiit.trikad.data;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
import java.util.List;
#Transactional
public interface AppointmentsRepository extends JpaRepository<Appointments, Long> {
List<Appointments> findByUserId(Long id);
}
Configuration is done by ApplicationContext file which (part of it) is the following:
<!-- Common. -->
<context:component-scan base-package="ee.bcs.valiit.trikad" />
<context:property-placeholder location="classpath:application.properties" file-encoding="UTF-8" />
<jpa:repositories base-package="ee.bcs.valiit.trikad.data" />
Application class
package ee.bcs.valiit.trikad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan ({"ee.bcs.valiit.trikad.data", "ee.bcs.valiit.trikad.service","ee.bcs.valiit.trikad.model", "ee.bcs.valiit.trikad.controller"})
public class TrikadApplication {
public static void main(String[] args) {
SpringApplication.run(TrikadApplication.class, args);
}
}
My build gradle file
buildscript {
ext {
springBootVersion = '2.0.4.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
ext {
springVersion = '5.0.8.RELEASE'
springDataVersion = '2.0.9.RELEASE'
hibernateVersion = '5.3.5.Final'
hibernateJpaVersion = '1.0.2.Final'
postgresqlVersion = '9.4.1212'
jacksonVersion = '2.9.6'
lombokVersion = '1.18.2'
slf4jVersion = '1.7.25'
junitVersion = '4.12'
}
}
apply plugin: 'war'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'ee.bcs.valiit'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile "org.springframework:spring-context-support:${springVersion}",
"org.springframework.data:spring-data-jpa:${springDataVersion}",
"org.springframework:spring-webmvc:${springVersion}",
"org.springframework:spring-web:${springVersion}",
"com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}",
"com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:${jacksonVersion}",
"org.springframework:spring-context-support:${springVersion}",
"org.hibernate:hibernate-entitymanager:${hibernateVersion}",
"org.hibernate.javax.persistence:hibernate-jpa-2.1-api:${hibernateJpaVersion}",
"com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}"
compile group: 'org.springframework.boot', name: 'spring-boot-dependencies', version: '2.0.4.RELEASE', ext: 'pom'
compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: '2.0.4.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.4.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-core', version: '5.0.7.RELEASE'
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
runtime "org.postgresql:postgresql:${postgresqlVersion}"
testCompile "junit:junit:${junitVersion}"
}
I have no idea what could be wrong. Can someone help me?

No matching factory method found:factory bean;factory method 'configurer()'.Check thatmethod with the specified name exists and that it is non-static

I am developing Spring Boot Batch XML based approach. In this example, I developed a CommonConfig like below. Somehow I wanted to use the XML based approach rather than using the annotation based approach for the Spring Batch.
CommonConfig.java
#StepScope
#Configuration
#ComponentScan({ "com.XXXX" })
#EnableBatchProcessing
#ImportResource({"classpath:jobs/ABC.xml"})
public class CommonConfig {
#Bean
BatchConfigurer configurer(
#Qualifier("dataSource") DataSource dataSource) {
return new DefaultBatchConfigurer(dataSource);
}
#Bean
public JobBuilderFactory jobBuilderFactory(JobRepository jobRepository) {
return new JobBuilderFactory(jobRepository);
}
#Bean
public StepBuilderFactory stepBuilderFactory(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilderFactory(jobRepository, transactionManager);
}
}
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configurer' defined in class path resource [com//config/CommonConfig.class]: No matching factory method found: factory bean 'commonConfig'; factory method 'configurer()'. Check that a method with the specified name exists and that it is non-static.
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:547) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at com.jpaApplication.main(jpaApplication.java:18) [classes/:na]
I struggled with this for about 1/2 hour and finally renamed my class from "Config" to "Configurations" and it worked. Maybe there was another "Config" somewhere? Who knows.
The EnableBatchProcessing annotation will automatically add the JobBuilderFactory and StepBuilderFactory (and other beans) to your application context (See its javadoc here: https://docs.spring.io/spring-batch/4.0.x/api/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html). So you don't need to define these beans yourself. What you need to do is to define your data source and it will be picked up by the DefaultBatchConfigurer:
#Configuration
#ComponentScan({ "com.XXXX" })
#EnableBatchProcessing
#ImportResource({"classpath:jobs/ABC.xml"})
public class CommonConfig {
#Bean
public DataSource dataSource() {
// return your data source
}
}
I would recommend following the getting started guide https://spring.io/guides/gs/batch-processing/ to see how to correctly configure and run a Spring Batch job with Spring Boot.

Spring WebMvcConfigurer running twice

I've noticed a strange behaviour in my Spring web application:
My WebMvcConfigurer implementation is running twice and I don't know why. I'm very new using Spring.
Here are all my classes I think are part of the problem. All of them are inside the same package br.com.cmabreu.config (ask if you need more information). I'm using 5.0.4.RELEASE:
#EnableWebMvc
#Configuration
public class WebConfig implements WebMvcConfigurer {
}
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super( LoginSecurityConfig.class );
}
}
#Configuration
#EnableWebSecurity
#ComponentScan(basePackages = "br.com.cmabreu.*")
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ComboPooledDataSource dataSource;
public void setDataSource(ComboPooledDataSource dataSource) {
this.dataSource = dataSource;
}
}
public class AppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
}
#Configuration
#EnableTransactionManagement
public class HibernateConfig {
#Bean(name="dataSource")
public ComboPooledDataSource getDataSource() {
ComboPooledDataSource driverManagerDataSource = new ComboPooledDataSource();
...
}
}
The execution order is:
1) SecurityWebApplicationInitializer
2) AppInitializer
3) HibernateConfig
4) WebConfig
5) LoginSecurityConfig
6) WebConfig ( AGAIN )
If I remove #ComponentScan from LoginSecurityConfig then the init sequence throws an error just after AppInitializer because it can't find HibernateConfig:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginSecurityConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mchange.v2.c3p0.ComboPooledDataSource' 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.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
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:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4641)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5105)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(Unknown Source)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:671)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mchange.v2.c3p0.ComboPooledDataSource' 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:1509)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 45 more
#EnableWebMvc annotation itself imports the Spring MVC configuration from WebMvcConfigurationSupport (with default methods).
You do not need to apply it to the class implementing WebMvcConfigurer (with default methods).

Spring Data Rest incompatible with Spring Data Neo4J?

I'm trying to incorporate Spring Data Rest into an application that is using Spring Data Neo4J. I get the following exception on start when I include Spring Data Rest into my application:
18:41:10.632 [main] INFO o.h.tool.hbm2ddl.SchemaUpdate - HHH000232: Schema update complete
18:41:11.280 [main] WARN o.e.j.u.component.AbstractLifeCycle - FAILED org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer#2521bcf2: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter': Injection of autowired dependencies failed; nested exception is ...
// very long stack trace here
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.neo4j.support.Neo4jTemplate]: Circular reference involving containing bean 'myApplication' - consider declaring the factory method as static for independence from its containing instance. Factory method 'neo4jTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'neo4jMappingContext': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 277 common frames omitted
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'neo4jMappingContext': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:285) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a.mappingInfrastructure(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate(Neo4jConfiguration.java:136) ~[spring-data-neo4j-3.3.1.RELEASE.jar:na]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a.CGLIB$neo4jTemplate$83(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a$$FastClassBySpringCGLIB$$484acc9c.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a.neo4jTemplate(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_71]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_71]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_71]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_71]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 278 common frames omitted
Here's my dependency list:
dependencies {
compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.springframework.cloud:spring-cloud-starter-aws")
compile("org.springframework.cloud:spring-cloud-aws-autoconfigure")
compile("commons-io:commons-io:2.4")
compile("org.springframework.boot:spring-boot-starter-data-rest")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.data:spring-data-neo4j:3.3.1.RELEASE")
compile("org.springframework.data:spring-data-commons:1.10.1.RELEASE")
compile("com.graphaware.neo4j:timetree:2.1.7.28.20")
compile("com.graphaware.neo4j:common:2.1.7.28")
compile("org.codehaus.jackson:jackson-mapper-asl:1.9.13")
// these are needed to provide Neo4J web admin interface
compile("org.neo4j.app:neo4j-server:2.1.8")
compile("org.neo4j.app:neo4j-server:2.1.8:static-web")
runtime("com.sun.jersey:jersey-server:1.17.1")
runtime("com.sun.jersey:jersey-servlet:1.17.1")
compile("org.codehaus.groovy:groovy")
runtime("org.postgresql:postgresql:9.4-1201-jdbc41")
//providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile "org.spockframework:spock-core:0.7-groovy-2.0"
}
The application runs as expected if I comment out compile("org.springframework.boot:spring-boot-starter-data-rest").
Is there a version mismatch perhaps?
EDIT to add config of main class as requested by Michael:
#Configuration
#EnableAutoConfiguration
#EnableAsync
#EnableScheduling
#SpringBootApplication
#EnableNeo4jRepositories(basePackages = "com.me.graph")
#EnableJpaRepositories(basePackages = "com.me.model")
#EnableTransactionManagement
class MyApplication extends Neo4jConfiguration implements CommandLineRunner {
MyApplication() {
setBasePackage("com.me.graph.domain");
}
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("graph/neo4j.db");
}
#Autowired
GraphDatabaseService db;
#Bean
public SingleTimeTree timeTree() {
return new SingleTimeTree(db)
}
#Autowired
LocalContainerEntityManagerFactoryBean entityManagerFactory;
#Override
#Bean(name = "transactionManager")
public PlatformTransactionManager neo4jTransactionManager(GraphDatabaseService db) throws Exception {
return new ChainedTransactionManager(new JpaTransactionManager(entityManagerFactory.getObject()),
new JtaTransactionManagerFactoryBean(graphDatabaseService()).getObject());
}
#Override
public void run(String... strings) throws Exception {
startNeo4jServer()
}
private static final Logger log = LoggerFactory.getLogger(MyApplication.class);
public void startNeo4jServer() {
// used for Neo4j browser
try {
WrappingNeoServerBootstrapper neoServerBootstrapper;
GraphDatabaseAPI api = (GraphDatabaseAPI) db;
ServerConfigurator config = new ServerConfigurator(api);
config.configuration()
.addProperty(Configurator.WEBSERVER_ADDRESS_PROPERTY_KEY, "127.0.0.1");
config.configuration()
.addProperty(Configurator.WEBSERVER_PORT_PROPERTY_KEY, "7474");
neoServerBootstrapper = new WrappingNeoServerBootstrapper(api, config);
neoServerBootstrapper.start();
} catch(Exception e) {
//handle appropriately
log.error("Exception when starting N4J")
}
// end of Neo4j browser config
}
static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
log.info("MyApplication started.");
}
}

#Autowired dependency is null in Groovy class implementing a Groovy interface

I am trying to inject a property class into a Groovy based class, but the injected class is null. I do have another properties class that is being injected into a class that is implementing from Tomcat's Filter interface and that is working fine.
Here is my stacktrace when starting the Spring Boot application:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stormpathAccountService' defined in file [/Users/jfitzgerald/Projects/parsezilla-api-partner/build/classes/main/com/schoolzilla/api/application/credentials/StormpathAccountService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.schoolzilla.api.application.credentials.StormpathAccountService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1077)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at 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 com.schoolzilla.api.Application.main(Application.groovy:18)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.schoolzilla.api.application.credentials.StormpathAccountService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1070)
... 20 more
Caused by: java.lang.NullPointerException
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.createGroovyObjectGetPropertySite(AbstractCallSite.java:254)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.acceptGroovyObjectGetProperty(AbstractCallSite.java:239)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at com.schoolzilla.api.application.credentials.StormpathAccountService.<init>(StormpathAccountService.groovy:37)
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:408)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 22 more
And here is the code that's giving me issues:
#Service
class StormpathAccountService implements AccountService {
//This is where my problem lies
#Autowired
StormpathProperties stormpathProperties
private def logger = LogFactory.getLog(StormpathAccountService)
private def path = System.getProperty("user.home") + stormpathProperties.apiKeyLocation
//more stuff here...
}
}
Groovy interface being implemented:
interface AccountService {
def createAccount(PartnerAccount account);
def deleteAccount(PartnerAccount account);
ApiKey fetchApiKey(PartnerAccount account);
}
Properties class:
#Configuration
#ConfigurationProperties(prefix = "stormpath")
class StormpathProperties {
String apiKeyLocation
String accountUrl
}
And the property names from my application.properties file:
stormpath.apiKeyLocation
stormpath.accountUrl
And finally my main Application class:
#Configuration
#ComponentScan
#EnableAutoConfiguration
#EnableTransactionManagement
#EnableConfigurationProperties
class Application {
static void main(String[] args) {
SpringApplication.run Application, args
}
}
I've looked through some other suggestions such as implementing a Java based interface instead of a Groovy based interface for classloader reasons, but so far that has not worked for me. I have also tried to change the method of injection to constructor based. The class is successfully injected, but the actual properties are then null.
I've spent a few days banging my head against the keyboard here, so any further help and/or explanation why it's not working would be greatly appreciated.
Edit:
Here is the other service that is using AccountService.groovy:
#Service
#Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
class PartnerApplicationService {
def logger = LoggerFactory.getLogger(PartnerApplicationService)
#Autowired
PartnerApplicationRepository repository
#Autowired
CredentialsRepository credentialsRepository
#Autowired
PartnerService partnerService
#Autowired
AccountService accountService
//lots more stuff...
}
I think you didn't inject the StormpathAccountService bean into the controller or another classe which uses it, if not try with injecting it:
#Autowired
StormpathAccountService stormpathAccountService;
OR:
inject the AccountService interface in it:
#Autowired
AccountService accountService;
Well, I think I found a solution that works for me. I wound up manually including the StormpathProperties file as part of the #ComponentScan. I have no idea why this needed to be explicit where everything else woks with #ComponentScan correctly.

Resources