Spring slice test with OAuth2 - java

I'm trying to make same slice test (#WebMvcTest) but the context of application is failing to start.
I write a simple test:
#WebMvcTest(value = [FeedbackEndpoint, FeedbackTestConfig])
class FeedbackEndpointSliceSpec extends Specification implements SampleFeedbacks {
#TestConfiguration
static class FeedbackTestConfig {
DetachedMockFactory detachedMockFactory = new DetachedMockFactory()
#Bean
FeedbackFacade feedbackFacade() {
return detachedMockFactory.Stub(FeedbackFacade)
}
}
#Autowired
FeedbackFacade feedbackFacade
#Autowired
MockMvc mockMvc
#WithMockUser
def "asking for non existing feedback should return 404"() {
given: "there is no feedback with the id I want"
UUID nonExistingId = UUID.randomUUID()
feedbackFacade.find(nonExistingId) >> { throw new FeedbackNotFoundException(nonExistingId) }
expect: "I get 404 and a message"
mockMvc.perform(get("/feedback/$nonExistingId"))
.andExpect(status().isNotFound())
}
}
When I try to run it, I've got an exception. I attach a stacktrace, I presume that it's caused by one of this annotation: #EnableAuthorizationServer, #EnableOAuth2Client, #EnableResourceServer
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:50)
at org.spockframework.spring.SpringInterceptor.interceptSetupMethod(SpringInterceptor.java:42)
at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:28)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:87)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration': Unsatisfied dependency expressed through field 'configurers'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurer>' 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:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1268)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 14 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurer>' 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:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 32 more
I tried already #WebMvcTest(value = [FeedbackEndpoint, FeedbackTestConfig], secure = false), but it didn't work either.
EDIT
In one topic on SO I found to add this annotation: #OverrideAutoConfiguration(enabled = true) and... it's working, but is it ok to add this?

Disabling #OverrideAutoConfiguration is no good as it may try to load whole application context to your turning your unit test to integration test.
You may be using #EnableAuthorizationServer in your #SpringBootApplication runner class, so test context is trying to load config classes for spinning AuthorizationServer. Try moving it to external configuration:
#Configuration
#EnableAuthorizationServer
public class AuthServerConfig {
}

Related

org.springframework.beans.factory.UnsatisfiedDependencyException occured. but I didn't change anything

org.springframework.beans.factory.UnsatisfiedDependencyException occured While I'm developing using Spring boot.
In to the point, I didn't change anything.
I tried check the fileUtil class, but there isn't any specific problem.
And did "Project clean" and reboot eclipse.
after searched on google, somebody says "check your annotation is valid"
so I checked annotations but there is nothing to guess
but error still not solved..
I'll show you my code
this is the exception.
심각: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileUtil': Unsatisfied dependency expressed through field 'config': No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties] found for dependency [com.m2u.chatbotany.common.utils.ConfigProperties]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties] found for dependency [com.m2u.chatbotany.common.utils.ConfigProperties]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4770)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties] found for dependency [com.m2u.chatbotany.common.utils.ConfigProperties]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570)
... 24 more
This is the stackTrace that I got from application after add #Component annotation.
심각: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileUtil': Unsatisfied dependency expressed through field 'config': No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties] found for dependency [com.m2u.chatbotany.common.utils.ConfigProperties]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties] found for dependency [com.m2u.chatbotany.common.utils.ConfigProperties]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:350)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4770)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties] found for dependency [com.m2u.chatbotany.common.utils.ConfigProperties]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1398)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1051)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1018)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:570)
... 24 more
and this is [com.m2u.chatbotany.common.utils.ConfigProperties]
(#Component <<- I added this annotation but nothing change )
public class ConfigProperties {
private static final Logger LOG = LoggerFactory.getLogger(ConfigProperties.class);
private Properties properties;
public ConfigProperties() {
LOG.info("ConfigProperties");
}
// ~ Implementation Method. ~~~~~~~~
// ~ Self Methods. ~~~~~~~~~~~~~~~~~
public final void init() {
// 환경 변수 설정 log 출력
if (this.properties != null) {
LOG.info("Initialize Config Variables");
// LOG.info(JsonUtil.marshallingJsonWithPretty(this.properties));
}
}
// ~ Getter and Setter
// ==============================================================================================
public final void setProperties(final Properties properties) {
this.properties = properties;
}
public final String getString(final String key) {
return this.properties.getProperty(key);
}
public final Integer getInteger(final String key) {
String value = this.properties.getProperty(key);
return new Integer(value);
}
}
This is fileUtil
/**
* 업로드 파일 유틸
*/
#Component("fileUtil")
public class FileUtil {
/**
* The constant LOG.
*/
private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class);
/**
* The Config.
*/
#Autowired
private ConfigProperties config;
......
}
This problem is I have never seen...
and my application had completely worked until 3 hours ago.
repeatly, I didn't change anything
waiting for your help.
No qualifying bean of type [com.m2u.chatbotany.common.utils.ConfigProperties]
Above error is because in FileUtil you have autowired ConfigProperties but ConfigProperties.class is not annotated with Stereotype (#Component, #Service etc)
So add the #Component annotation like below
#Component
public class ConfigProperties {
// Code logic
}

Spring Boot with Sping Data Redis cannot start without Sentinel connections

this is my first question so pardon me if the way I phrase the questions still need improvement
I am currently working on a Spring Boot Web Application which uses Redis as a Cache to prevent excessive calls to external APIs. In that sense, Spring is actually good to have but not a necessity.
The structure of the project is as the follow
1.) A persistence module containings DAO classes that compiles spring-data-redis project and uses RedisTemplate with #Autowired annotation
Example RedisDao class(I am not using the exact implementation due to private code reasons):
#Autowired
private RedisTemplate redisTemplate
public AuthInfoDto createAuthInfo(Integer memberId, Integer expiry) {
//Some method to generate key
String key = createAuthKey(memberId)
redisTemplate.opsForValue().set(key, memberId)
}
This project is then built with gradle clean install to generate the jar file to be imported by main project
2.) The main project then compiles the persistence project and I set up configuration in this main project
#Configuration
#Lazy
public class RedisConfigure {
#Bean
#Lazy
public RedisTemplate<String, Integer> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory)
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
The problem is that; when Sentinel is not available or there's a connection error to Sentinel. The Spring Boot application cannot start
I have tried adding #Lazy annotations to all the beans and configuration files including that in the persistence module but its still not working.
Something I notice is that JedisConnectionFactory automatically throws an exception if it cannot detect any Sentinel during startup.
May I know if there are any ways I can prevent spring boot from trying to connect to Sentinel during startup?
Thank you very much
EDIT
Here is the error code. As for JedisConnectionFactory Bean; I let spring-data-redis auto configuration handle it for me so i just set the required properties in my application.yml file
spring.redis:
pool:
max-idle: 10
min-idle: 5
sentinel:
master: redis-cluster
nodes: sentinelhost1:port1,sentinelhost2:port2,sentinelhost3:port3
ERROR
13:20:01.381 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisReferenceResolver': Cannot resolve reference to bean 'redisTemplate' while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisTemplate' defined in class path resource [sg/com/rakuten/rewards/rpg/api/domain/configure/RedisCacheConfigure.class]: Unsatisfied dependency expressed through method 'redisTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConnectionConfiguration.class]: Invocation of init method failed; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: All sentinels down, cannot determine where is redis-cluster master is running...
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
at sg.com.rakuten.rewards.rpg.api.RPGApiApplication.main(RPGApiApplication.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisTemplate' defined in class path resource [sg/com/rakuten/rewards/rpg/api/domain/configure/RedisCacheConfigure.class]: Unsatisfied dependency expressed through method 'redisTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConnectionConfiguration.class]: Invocation of init method failed; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: All sentinels down, cannot determine where is redis-cluster master is running...
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 26 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration$RedisConnectionConfiguration.class]: Invocation of init method failed; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: All sentinels down, cannot determine where is redis-cluster master is running...
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 36 common frames omitted
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: All sentinels down, cannot determine where is redis-cluster master is running...
at redis.clients.jedis.JedisSentinelPool.initSentinels(JedisSentinelPool.java:180)
at redis.clients.jedis.JedisSentinelPool.<init>(JedisSentinelPool.java:95)
at redis.clients.jedis.JedisSentinelPool.<init>(JedisSentinelPool.java:76)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.createRedisSentinelPool(JedisConnectionFactory.java:263)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.createPool(JedisConnectionFactory.java:248)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.afterPropertiesSet(JedisConnectionFactory.java:237)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 47 common frames omitted
The exception you're seeing comes from JedisConnectionFactory.afterPropertiesSet(). You need to set all Redis-related beans to #Lazy, also the connection factory.
You would need to declare your own JedisConnectionFactory bean. Alternatively, try using the Lettuce driver as Lettuce attempts to resolve a Redis server rather lazily.

Junit testing independent Service layer in springboot

I have independent service layer packed as jar maven module. Also Dao layer.
(basically 3 projects 1 for controllers, 1 service, 1 dao)
All the configurations and MainSpringBootApplication.java is in controller layer. At controller unit tests work just fine with below annotations.
#SpringBootTest
#RunWith(SpringRunner.class)
#ActiveProfiles("testenv")
Now I want to unit test service layer as well. But facing error.
Service layer class has below annotations
#RunWith(SpringRunner.class)
#ActiveProfiles("testenv")
#PropertySource("classpath:application-testenv")
it gives error like below
Same is the case with Dao layer.
How to configure spring for unit test with test.properties file for such project structure.
Note : I am using NO XML configuration.
Any help is appreciated.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.test.example.TestSrevice': Unsatisfied dependency expressed through field 'testService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.example.TestSrevice' 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:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.example.TestSrevice' 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:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 28 more
Edit
Error trace after suggested changes
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testService': Unsatisfied dependency expressed through field 'testDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.example.TestDao' 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:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.example.TestDao' 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:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 43 more
You can provide some test configuration to use with your unit test using the #ContextConfiguration annotation. If it's just a #ComponentScan you need to use I would recommend just using a static inner class for your configuration in your test class. Annotating your test class with #ContextConfiguration with no parameters will default to that inner class for configuration:
#RunWith(SpringRunner.class)
#ActiveProfiles("testenv")
#PropertySource("classpath:application-testenv")
#ContextConfiguration
public class MyServiceTest {
...
#ComponentScan
#Configuration
public static class MyServiceTestConfiguration {
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
}
I also included a PropertySourcesPlaceholderConfigurer bean because I'm pretty sure you'll also need that to read your properties correctly.
Based on your failure below, it confirms that your DAO's aren't being created. Perhaps they aren't being scanned in which case you'd need to ensure the packages do get scanned. If they are getting scanned but the DAOs aren't getting created, the issue may be that JPA isn't loading.
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'com.test.example.TestDao' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
You may want to add the following annotation to your tests:
#DataJpaTest, as specified in the #DataJpaTest documentation:
Annotation that can be used in combination with
#RunWith(SpringRunner.class) for a typical JPA test. Can be used when
a test focuses only on JPA components. Using this annotation will
disable full auto-configuration and instead apply only configuration
relevant to JPA tests.
By default, tests annotated with #DataJpaTest will use an embedded
in-memory database (replacing any explicit or usually auto-configured
DataSource). The #AutoConfigureTestDatabase annotation can be used to
override these settings.
If you are looking to load your full application configuration, but
use an embedded database, you should consider #SpringBootTest combined
with #AutoConfigureTestDatabase rather than this annotation.
Thanks #Plog and #JC Carrillo I was missing #DataJpaTest and additionally #EntityScan("com.test") and #EnableJpaRepositories("com.test") This solved the problem but still my test fails because it is not taking configurations of h2 database from given properties file and boot trys to manage it on its own.

Inject custom feign client into Spring Application

I am currently trying to get a grip of both Spring and Feign.
Cutting straight to the point:
I am struggling to modify #FeignClient in this project:
Feign Hello World by Walery
so as to instead of
WikidataClient
#FeignClient(url = "https://www.wikidata.org/w")
// https://www.wikidata.org/w/api.php?action=wbsearchentities&search=apple&language=en&format=json
public interface WikidataClient {
#RequestMapping(value = "/api.php?action=wbsearchentities&language=en&format=json", method = GET)
WebsearchEntities searchForEntities(#RequestParam("search") final String search);
}
use #Autowired notation similar to one found here: Section called : Creating Feign Clients Manually
The purpose of this would be to inject custom decoder and encoder later on. I've been exprimenting with it for a while and all I managed to achieve was ruin the whole thing.
I gathered some clues from here and there and managed to come to the point where I created a Configuration class :
FeignConfig
#Import(FeignClientsConfiguration.class)
public class FeignConfig {
public WikidataClient fooclient;
#Autowired
public FeignConfig(Encoder encoder, Decoder decoder){
this.fooclient = Feign.builder()
.encoder(encoder)
.decoder(decoder)
.target(WikidataClient.class,"https://www.wikidata.org/w");
}
}
Modified
WikidataClient
interface slightly
//#FeignClient(url = "https://www.wikidata.org/w")
// https://www.wikidata.org/w/api.php?action=wbsearchentities&search=apple&language=en&format=json
public interface WikidataClient {
#RequestMapping(value = "/api.php?action=wbsearchentities&language=en&format=json", method = GET)
WebsearchEntities searchForEntities(#RequestParam("search") final String search);
}
and tried to use aforementioned class instead
WikidataRunner
#Component
public class WikidataRunner implements CommandLineRunner {
private final WikidataClient omdbClient;
#Autowired
public WikidataRunner(WikidataClient omdbClient){
this.omdbClient = omdbClient;
this.feignConfig = new FeignConfig(new Encoder.Default(), new Decoder.Default());
}
FeignConfig feignConfig;
#Override
public void run(final String... args) throws Exception {
final WebsearchEntities apple = feignConfig.fooclient.searchForEntities("apple");
System.out.println(apple);
}
}
All I got were different kind of Bean errors
2017-07-19 08:02:29.056 ERROR 2018 --- Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'wikidataRunner' defined in file
[/home/mibi/IdeaProjects/FUFEign/feign-helloworld/target/classes/codes/walery/research/feign/wikidata/WikidataRunner.class]:
Unsatisfied dependency expressed through constructor argument with
index 0 of type [codes.walery.research.feign.wikidata.WikidataClient]:
: No qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {}; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {} [
main] at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
o.s.boot.SpringApplication at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
: Application startup failed at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {} at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:667)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.boot.SpringApplication.doRun(SpringApplication.java:342)
... 18 common frames omitted at
org.springframework.boot.SpringApplication.run(SpringApplication.java:273)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:980)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:969)
at
codes.walery.research.feign.FeignHelloworldApplication.main(FeignHelloworldApplication.java:12)
Wrapped by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'wikidataRunner' defined in file
[/home/mibi/IdeaProjects/FUFEign/feign-helloworld/target/classes/codes/walery/research/feign/wikidata/WikidataRunner.class]:
Unsatisfied dependency expressed through constructor argument with
index 0 of type [codes.walery.research.feign.wikidata.WikidataClient]:
: No qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {}; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 beCaused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {} at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
an which qualifies as autowire candidate for this dependency.
Dependency annotations: {} at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] ... 18 more at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
~[spring-beans-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
~[spring-context-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
~[spring-context-4.2.1.RELEASE.jar:4.2.1.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:667)
[spring-boot-1.3.0.M5.jar:1.3.0.M5] at
org.springframework.boot.SpringApplication.doRun(SpringApplication.java:342)
[spring-boot-1.3.0.M5.jar:1.3.0.M5] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:273)
[spring-boot-1.3.0.M5.jar:1.3.0.M5] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:980)
[spring-boot-1.3.0.M5.jar:1.3.0.M5] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:969)
[spring-boot-1.3.0.M5.jar:1.3.0.M5] at
codes.walery.research.feign.FeignHelloworldApplication.main(FeignHelloworldApplication.java:12)
[classes/:na] 2017-07-19 08:02:29.059 INFO 2018 --- [ Thread-1]
s.c.a.AnnotationConfigApplicationContext : Closing
org.springframework.context.annotation.AnnotationConfigApplicationContext#3d8314f0:
startup date [Wed Jul 19 08:02:24 CEST 2017]; root of context
hierarchy
Process finished with exit code 1
I won't deny being novice at Spring and Feign. Thing is I need to undestand both of these desperately. So far I've spent 10+ hours researching about Feign to no avail.
Kindly asking for help and guidance
MissingBracket
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[codes.walery.research.feign.wikidata.WikidataClient] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency.
try to declare a bean somewhere:
#Bean
public WikiDataClient wikiDataClient () {
}
Construct feign client with feign builder manually:
Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract).target(WikiDataClient.class, "http://serviceId")

Java Spring annotation error

I'm writing a web application using Spring MVC, I have en error, and I don`t know what's causing it.
I was looking for any solution but adding annotations like #Component didn't help.
Here is the code of classes:
Repository class:
#Repository("UserRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
#Query("Insert INTO User Values(email,password)")
public User AddUser(#Param("email") String email, #Param("password") String password);
}
Controller class:
#RestController
public class UserActionController {
private UserRepository userservice;
#Autowired
public UserActionController(UserRepository userservice)
{
this.userservice = userservice;
}
#RequestMapping(value = { "/zaloguj" }, method = RequestMethod.GET)
public ModelAndView logowanie(#RequestParam String action) {
ModelAndView model = new ModelAndView();
model.addObject("title", "Injected MVC title");
model.addObject("message", "This is default page!");
model.setViewName("zaloguj");
userservice.AddUser("test", "test");
return model;
}
}
And the error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userActionController' defined in file [C:\Users\bartlomiej.zuk\workspaceEclipse4\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\examplespringproject\WEB-INF\classes\com\mkyong\web\controller\UserActionController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.mkyong.dao.UserRepository]: : No qualifying bean of type [com.mkyong.dao.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mkyong.dao.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:838)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5236)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mkyong.dao.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 24 more
No qualifying bean of type [com.mkyong.dao.UserRepository]
This means that spring could not instantiate the UserRepository. You somehow should tell the spring where's your repositories location. For example, you should have a Data Access Configuration like following:
#Configuration
#EnableJpaRepositories(basePackages="com.mkyong.dao")
public class DataConfig {
// Put your DataSource, EntityManagerFactory, PlatformTransactionManager, etc here
}
basePackages="com.mkyong.dao" tells the spring container to look for repositories in com.mkyong.dao package. Also, when you're using Spring Data, there is no need for #Repository annotations.

Categories