I have written one mail utility for my project. Now when I try to
#Autowired
EmailManager emailManager
from my UserController I am getting the error saying that the bean can not be created.
here I am displaying the code written in Class EmailManager
#Component
public class EmailManager {
#Autowired
ApplicationContext appContext;
#Autowired
ThreadPoolTaskExecutor taskExecutor;
public Logger logger = Logger.getLogger(EmailManager.class);
public boolean sendChangePasswordNotification(String password,UserVO userVo) throws Exception{
try {
logger.info("Send change password notification to " + userVo.getEmailId());
String cc = PropertyUtil.getProperty("cc");
logger.info("cc:"+cc);
HashMap<String,String> replaceKeyValue = new HashMap<String,String>();
replaceKeyValue.put("username", userVo.getUsername());
replaceKeyValue.put("password", password);
replaceKeyValue.put("firstName", userVo.getFirstName());
HashMap<String,String> recipientMap = new HashMap<String,String>();
recipientMap.put("to", userVo.getEmailId());
recipientMap.put("cc", cc);
MailThread sender1 = (MailThread) appContext.getBean(MailThread.class);
sender1.setEmailOption(Constants.SEND_CHANGE_PASSWORD_NOTIFICATION);
sender1.setRecipientDetails(recipientMap);
sender1.setReplaceKeyValue(replaceKeyValue);
taskExecutor.execute(sender1);
logger.info("Sent change password notification to " + userVo.getEmailId());
} catch (Exception e) {
logger.error("Error", e);
throw e;
}
return true;
}
}
And here is the full stack trace which I got on eclipse console:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emailManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor com.isynergy.tasktrac.notification.EmailManager.taskExecutor; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] found for dependency: 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.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:326)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
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:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4772)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
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.BeanCreationException: Could not autowire field: org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor com.isynergy.tasktrac.notification.EmailManager.taskExecutor; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] found for dependency: 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:542)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:323)
... 22 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] found for dependency: 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:1261)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1009)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
How can I tackle this problem any suggestion?
EmailManager can't be created since it has declared a dependency for ThreadPoolTaskExecutor, and no applicable beans of that type is present in the application context. You need to create a bean of type ThreadPoolTaskExecutor to the application context.
Related
I have a Spring Boot Rest API that I've been working, and I added Swagger and Swagger-UI last week. After that, the tests of the repositories(ONLY tests related with the repository) started to not working and when I run them I get this error:
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.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.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
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:51)
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 'documentationPluginsBootstrapper' defined in URL [jar:file:/C:/Users/Ale/.m2/repository/io/springfox/springfox-spring-web/2.3.1/springfox-spring-web-2.3.1.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/C:/Users/Ale/.m2/repository/io/springfox/springfox-spring-web/2.3.1/springfox-spring-web-2.3.1.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
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.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)
... 33 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/C:/Users/Ale/.m2/repository/io/springfox/springfox-spring-web/2.3.1/springfox-spring-web-2.3.1.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
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: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)
... 51 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
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.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 65 more
I don't know why this error is happening, because these tests are not related with Swagger.
The configuration code is like this:
#EnableSwagger2
#SpringBootApplication
public class UserServiceApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage(getClass().getPackage().getName()))
.paths(PathSelectors.any())
.build()
.apiInfo(generateApiInfo());
}
private ApiInfo generateApiInfo() {
return new ApiInfo("User Service", "User Service", "", "", "", "", "");
}
}
The POM file is like this, with Swagger 2.3.1:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${io.springfox.springfox-swagger2}</version>
</dependency>
<!-- Include swagger for API description UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${io.springfox.springfox-swagger-ui}</version>
</dependency>
And the test is very simple:
#RunWith(SpringRunner.class)
#DataJpaTest
#Transactional
public class UserRepositoryTest {
#Autowired
private TestEntityManager entityManager;
#Autowired
private UserRepository userRepository;
#Test
public void whenPersistingAnUserTheUserAndImageAreSaved(){
UserImage userImage = new UserImage("key","URL");
User user = new User("email#mail.com", "pass","name","lastNmae","description","123123",userImage);
User savedUser = userRepository.save(user);
assertNotNull(savedUser.getId());
assertNotNull(savedUser.getUserImage().getId());
}
Could you help me please? The rest of the tests work correctly.
Thanks!
The problem is that your central configuration class UserServiceApplication is setting up Swagger and Spring MVC. When you use #DataJpaTest, you are effectively telling Spring Boot not to load the Spring MVC related infrastructure. But... some of the beans created by #EnableSwagger2 expect the MVC infrastructure to be in place, which is not the case with #DataJpaTest.
Thus, in order to benefit from Spring Boot's test slicing support (i.e., #DataJpaTest), you'll need to move the Swagger and MVC configuration to a separate #Configuration class.
I have answered here as well:
https://stackoverflow.com/a/52670119/8553816.
1. Extend swagger with WebMvcConfigurerAdapter adapter and override addResourceHandlers method like mentioned below along with swagger config methods:
#Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
Note: WebMvcConfigurerAdapter is deprecated in spring 5 so use WebMvcConfigurationSupport in spring 5 and later.
2. Make sure your test class is also annotated with #SpringBootTest, #RunWith(SpringRunner.class) alongwith #datajpatest.
Tip: Create a custom annotation and add bunch of other annotations loke #transactional etc. and use this custom annotation on repo test classes.
3. Its better to have a different spring profile to run test cases and dont forget to annotate the test class with #ActiveProfiles("profileHere").
Hope solution works!
Also, make sure to have your swagger configuration out of the #SpringBootApplication class, including the #EnableSwagger2 annotation:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
// ...
}
Error description
:org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0':
Invocation of init method failed; nested exception is
java.lang.IllegalStateException: Ambiguous mapping found. Cannot map
'xyz' bean method public
v1.com.practiceproject.response.ResponseObject
v1.com.practiceproject.service.xyz.getSelectedProduct(java.lang.String) throws java.lang.Exception to
{[/person/person],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}:
There is already 'personService' bean method public
v1.com.practiceproject.response.ResponseObject
v1.com.practiceproject.service.PersonService.getSelectedProduct(java.lang.String)
throws java.lang.Exception mapped. at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
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:
java.lang.IllegalStateException: Ambiguous mapping found. Cannot map
'xyz' bean method public
v1.com.practiceproject.response.ResponseObject
v1.com.practiceproject.service.xyz.getSelectedProduct(java.lang.String) throws java.lang.Exception to
{[/person/person],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}:
There is already 'personService' bean method public
v1.com.practiceproject.response.ResponseObject
v1.com.practiceproject.service.PersonService.getSelectedProduct(java.lang.String)
throws java.lang.Exception mapped. at
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:176)
at
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:148)
at
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:109)
at
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:89)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:163)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 21 more
As your Stack trace shows you have "Ambiguous mapping found. Cannot map 'xyz' bean method public" "There is already 'personService' bean method" as i guess your two #RequestMapping urls are same.
Actually I'm new to spring-boot concept, my problem is when I run my program in eclipse I get the error as shown below, Problem is i dint got what the error is and how to solve this.., So some one help me to fix this error
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityFilterChainRegistration' defined in class path resource [org/springframework/boot/autoconfigure/security/SpringBootWebSecurityConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [javax.servlet.Filter]: : Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ignoredPathsWebSecurityConfigurerAdapter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration$IgnoredPathsWebSecurityConfigurerAdapter.endpointHandlerMapping; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpointHandlerMapping' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping]: Factory method 'endpointHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcEndpoints' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'environmentMvcEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.boot.actuate.endpoint.EnvironmentEndpoint]: : Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration.healthIndicators; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration.dataSources; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration.healthIndicators; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration.dataSources; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ignoredPathsWebSecurityConfigurerAdapter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration$IgnoredPathsWebSecurityConfigurerAdapter.endpointHandlerMapping; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpointHandlerMapping' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping]: Factory method 'endpointHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcEndpoints' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'environmentMvcEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.boot.actuate.endpoint.EnvironmentEndpoint]: : Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration.healthIndicators; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration.dataSources; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration.healthIndicators; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration$DataSourcesHealthIndicatorConfiguration.dataSources; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1117)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1012)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.boot.context.embedded.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:211)
at org.springframework.boot.context.embedded.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:85)
at org.springframework.boot.context.embedded.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:73)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getServletContextInitializerBeans(EmbeddedWebApplicationContext.java:233)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:220)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:84)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:205)
at org.springframework.boot.context.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:54)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5170)
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$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
This contain main method:-
package com.tanmay;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import com.javatpoint.Controller;
import com.tanmay.vo.Column;
import com.tanmay.vo.Database;
import com.tanmay.vo.Table;
import com.tanmay.vo.Column.ColType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class LoadExcelSheet {
#RequestMapping("/ExcelVisualize")
#ResponseBody
public void loadExcelSheet(String excelFilePath) throws Exception {
FileInputStream inputStream = new FileInputStream(new File(
excelFilePath));
Database DatabaseObj = new Database();
DatabaseObj.DatabaseName = "Tanmay";
Workbook workbook = new XSSFWorkbook(inputStream);
String CreationScript="";
for (int WorksheetNum = 0; WorksheetNum < workbook.getNumberOfSheets(); WorksheetNum++) {
Sheet firstSheet = workbook.getSheetAt(WorksheetNum);
Table TableObj = new Table();
TableObj.TableName = firstSheet.getSheetName();
int lrow = firstSheet.getPhysicalNumberOfRows();
Row ColumnRow = firstSheet.getRow(0);
Row DataTypeRow = firstSheet.getRow(1);
for (int x = 2; x<lrow; x++) {
Row DataValueRow = firstSheet.getRow(x);
Iterator<Cell> cellIterator = ColumnRow.cellIterator();
int columnNum = 0;
//int rowNum=0;
while (cellIterator.hasNext()) {
cellIterator.next();
Column ColumnObj = new Column();
Row RowObj = null;
Cell ColCell = ColumnRow.getCell(columnNum);
Cell DataTypeCell = DataTypeRow.getCell(columnNum);
Cell DataValueCell = DataValueRow.getCell(columnNum);
switch (ColCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
ColumnObj.ColumnName = ColCell.getStringCellValue();
break;
}
// values
try{
switch (DataValueCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
ColumnObj.ColumnValues = DataValueCell
.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
ColumnObj.numColumnValues = (int)DataValueCell.getNumericCellValue();
break;
/*
* case Cell.CELL_TYPE_BOOLEAN: ColumnObj.num1ColumnValues =
* (DataValueCell .getBooleanCellValue());
*/
default:
break;
}
ColumnObj.ColLocationNumber = columnNum;
switch (DataTypeCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
String DataType = DataTypeCell.getStringCellValue();
if (DataType.toLowerCase().startsWith("pk.")) {
// PK.string
ColumnObj.isPrimaryKey = true;
ColumnObj.ColumnType = getDataType(DataType.split(
"\\.", 2)[1]);
} else if (DataType.toLowerCase().startsWith("fk.")) {
// fk.string.tablename.columnname
ColumnObj.isForeignKey = true;
ColumnObj.ColumnType = getDataType(DataType.split(
"\\.", 4)[1]);
ColumnObj.ForeignKey_Table = DataType.split("\\.",
4)[2];
ColumnObj.ForeignKey_Column = DataType.split("\\.",
4)[3];
} else {
ColumnObj.ColumnType = getDataType(DataType);
}
break;
}
if (!ColumnObj.ColumnName.equals(""))
TableObj.Columns.put(ColumnObj.ColumnName, ColumnObj);
columnNum++;
}catch(Exception e){}
}
if(x>1)
{
CreationScript += TableObj.getInsertScript()+"\n";
}
}
DatabaseObj.Tables.put(TableObj.TableName, TableObj);
}
System.out.println(DatabaseObj.getCreationScript());
System.out.println(CreationScript);
// Prepared statement
workbook.close();
inputStream.close();
}
private ColType getDataType(String DataType) {
if (DataType.toLowerCase().equals("string")) {
return ColType.STRING;
} else if (DataType.toLowerCase().equals("int")) {
return ColType.INTEGER;
} else if (DataType.toLowerCase().equals("date")) {
return ColType.DATE;
}
return ColType.NONE;
}
public static void main(String[] args) throws Exception {
new LoadExcelSheet().loadExcelSheet("c:\\Userdetails.xlsx");
}
}
ExcelVisualizeApplication:-
package com.tanmay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ExcelVisualizeApplication {
public static void main(String[] args) {
SpringApplication.run(ExcelVisualizeApplication.class, args);
}
}
There's a lot of stack trace there to look at and no code to debug. But the one part that stands out to me is the part that says "If you want an embedded database please put a supported one on the classpath.".
Because you've only shared a stack trace and no code, I can only speculate what's going on, but it appears as if a data source is needed, but can't be created because there's no suitable embedded database library (such as H2, Hypersonic, or Derby) on the classpath. I can't say for sure, but I believe that the part about setting up the Spring Security filters is just a side effect of not having that data source.
But again, without knowing what, if any beans you've configured (is Boot doing all of the autoconfig or have you explicitly configured any beans?) I'm only able to point out the datasource error.
I'm needing to #Autowire a Spring Data Neo4J repository into a Spring MVC converter (in Spring Boot), but the MVC configuration gets started before the Data services get started. This results in an #Autowired not found problem. How do I get the Data Services to get started before the MVC so it finds an eligible bean?
I have a project I'm converting from XML Spring config to Spring Boot. Everything is working fine except for the MVC Converters. They are not able to #Autowire Neo4J Repository classes.
If remove the #Autowire of the Repository and hard code in a value, things work as expected with the hack. Other operations in services are using the Repositories just fine. It seems the MVC config is getting started before the Neo4J plumbing can get started and then can't find the right components to tie into. I've looked, but I can't figure out how to get the data config to start before the MVC config.
Here's my base config:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Toyfiles {
public static void main(String[] args) throws Exception {
SpringApplication.run(Toyfiles.class, args);
}
}
My MVC Config:
#Configuration
public class MVCBeans extends WebMvcConfigurerAdapter {
#Autowired
private StringToBrand stringToBrand;
#Autowired
private BrandToString brandToString;
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(stringToBrand);
registry.addConverter(brandToString);
super.addFormatters(registry);
}
}
The offending Converter:
#Component
public class StringToBrand implements Converter<String, Brand> {
#Autowired
BrandRepository brandRepository;
#Override
public Brand convert(String s) {
return brandRepository.findBrandByName(s);
}
}
The Data config:
#Configuration
#Profile("localEmbeddedDBServer")
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "com.toyfiles.dataservices.")
public class LocalDBConfig extends Neo4jConfiguration {
public LocalDBConfig() {
setBasePackage("com.toyfiles");
}
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("target/graph.db");
}
}
And the Repository:
public interface BrandRepository extends GraphRepository<Brand> {
#Query(value = "MATCH (brand:Brand {name:{0}})-[:PART_OF]->line RETURN line")
public List<Line> getLinesForBrand(String name);
#Query(value = "MATCH (brand:Brand {name:{0}}) DELETE brand")
public void deleteBrandByName(String name);
public Brand findBrandByName(String name);
}
The "interesting" part of the Exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brandRepository': Cannot resolve reference to bean 'neo4jTemplate' while setting bean property 'neo4jTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1457)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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.findAutowireCandidates(DefaultListableBeanFactory.java:1021)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:964)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:481)
... 116 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
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.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 129 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 138 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
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.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:288)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.mappingInfrastructure(<generated>)
at org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate(Neo4jConfiguration.java:135)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.CGLIB$neo4jTemplate$23(<generated>)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6$$FastClassBySpringCGLIB$$12e74a61.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.neo4jTemplate(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 139 more
Caused by: java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:346)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:333)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:307)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:181)
at org.springframework.data.neo4j.mapping.RelationshipInfo.<init>(RelationshipInfo.java:65)
at org.springframework.data.neo4j.mapping.RelationshipInfo.fromField(RelationshipInfo.java:79)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.extractRelationshipInfo(Neo4JPersistentPropertyImpl.java:128)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.<init>(Neo4JPersistentPropertyImpl.java:80)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:161)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:449)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:606)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:181)
at org.springframework.data.neo4j.mapping.RelationshipInfo.<init>(RelationshipInfo.java:65)
at org.springframework.data.neo4j.mapping.RelationshipInfo.fromField(RelationshipInfo.java:79)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.extractRelationshipInfo(Neo4JPersistentPropertyImpl.java:128)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.<init>(Neo4JPersistentPropertyImpl.java:80)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:161)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:449)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:606)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:257)
at org.springframework.data.mapping.context.AbstractMappingContext.initialize(AbstractMappingContext.java:373)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.initialize(Neo4jMappingContext.java:111)
at org.springframework.data.mapping.context.AbstractMappingContext.afterPropertiesSet(AbstractMappingContext.java:363)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 160 more
I used an #Lazy annotation for the repository to delay the reference to the repository since the repository was getting started correctly later in the startup. This allowed the repository reference to be delayed until it was needed and available.
#Autowired
#Lazy
BrandRepository brandRepository;
I am new to writing test cases:
My controller is below :
#RequestMapping(value={"/addschool" }, method = RequestMethod.GET)
public final ModelAndView addschool(#ModelAttribute("addschool") Pricing pricing, Map<String, Object> map,
Model model, HttpServletRequest request) {
System.out.println("Name=" + pricing.getName() + " age=" + request.getParameter("age"));
ModelAndView mv = new ModelAndView(ADDSCHOOL);
return mv;
}
and my junit test case is this :
public class AddSchoolTest {
#Autowired
private UserManagementController controller;
#Test
public void testAddSchool() {
ModelMap model = new ModelMap();
HttpServletRequest request = new MockHttpServletRequest();
Pricing pricing = new Pricing();
String userName = "Laily";
pricing.setName(userName);
//ModelAndView mav= controller.handleRequest();
try{
ModelAndView mav= controller.addschool(pricing, model,null, request);
//fail("Not yet implemented");
assertNull(pricing);
assertFalse(model.isEmpty());
Assert.assertEquals("addschool", mav.getViewName());
}catch(Exception e){
}
}
}
but my problem is even if I will remove "add school" and put something else it wil show green but if I remove try and catch than in every case it wil give red. What is the problem.
Full stack trace is this
Error creating bean with name 'com.enbee.admin.controller.AddSchoolTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.enbee.admin.controller.AddInstiDeptLibController com.enbee.admin.controller.AddSchoolTest.controller; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.enbee.admin.controller.AddInstiDeptLibController] found for dependency: 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.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
aused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.enbee.admin.controller.AddInstiDeptLibController com.enbee.admin.controller.AddSchoolTest.controller; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.enbee.admin.controller.AddInstiDeptLibController] found for dependency: 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:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.enbee.admin.controller.AddInstiDeptLibController] found for dependency: 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:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
As pappu_kity says, removing the empty catch block exposes the fact that your controller field is null - and so probably hasn't been autowired.
To ensure that the field is autowired using #Autowired you need to run the test with the SpringJUnit4ClassRunner by annotating the AddSchoolTest class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath*:/path/to/applicationContext.xml" })
public class AddSchoolTest {
#Autowired
private UserManagementController controller;
#Test
public void testAddSchool() throws Exception {
ModelMap model = new ModelMap();
HttpServletRequest request = new MockHttpServletRequest();
Pricing pricing = new Pricing();
String userName = "Laily";
pricing.setName(userName);
//ModelAndView mav= controller.handleRequest();
ModelAndView mav= controller.addschool(pricing, model,null, request);
//fail("Not yet implemented");
assertNull(pricing);
assertFalse(model.isEmpty());
Assert.assertEquals("addschool", mav.getViewName());
}
}
Ensure that the #ContextConfiguration is set appropriately for the locations of your Spring config files.
you can try changing
ModelAndView mv = new ModelAndView(ADDSCHOOL);
to
ModelAndView mv = new ModelAndView(addschool); or
ModelAndView mv = new ModelAndView(pricing);
as it is in the #ModelAttribute("addschool") Pricing pricing
in your controller action .
I am not sure but just can see whether it works or not
Thanks.
if it is red then your test case is falling, your catch block is empty, print the stack trace and see what is the problem , upon exception your test case will fail.