I would like to use Gson for webservices in spring 4. I followed steps in this tutorial.
SocialGraphUI-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="socialgraphui.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/scripts/**" location="/scripts/" />
<mvc:resources mapping="/styles/**" location="/styles/" />
<mvc:annotation-driven />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.example.converter.GsonMessageConverter" />
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="true" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
GsonMessageConverter.java
public class GsonMessageConverter extends AbstractHttpMessageConverter<Object>
implements GenericHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Gson _gson;
private Type _type = null;
private boolean _prefixJson = false;
/**
* Construct a new {#code GsonMessageConverter} with a default
* {#link Gson#Gson() Gson}.
*/
public GsonMessageConverter() {
this(new Gson());
}
/**
* Construct a new {#code GsonMessageConverter}.
*
* #param serializeNulls
* true to generate json for null values
*/
public GsonMessageConverter(boolean serializeNulls) {
this(serializeNulls ? new GsonBuilder().serializeNulls().create()
: new Gson());
}
/**
* Construct a new {#code GsonMessageConverter}.
*
* #param gson
* a customized {#link Gson#Gson() Gson}
*/
public GsonMessageConverter(Gson gson) {
super(new MediaType("application", "json", DEFAULT_CHARSET));
setGson(gson);
}
/**
* Sets the {#code Gson} for this view. If not set, a default
* {#link Gson#Gson() Gson} is used.
* <p>
* Setting a custom-configured {#code Gson} is one way to take further
* control of the JSON serialization process.
*
* #throws IllegalArgumentException
* if gson is null
*/
public void setGson(Gson gson) {
Assert.notNull(gson, "'gson' must not be null");
_gson = gson;
}
public void setType(Type type) {
this._type = type;
}
public Type getType() {
return _type;
}
/**
* Indicates whether the JSON output by this view should be prefixed with
* "{} &&". Default is false.
* <p>
* Prefixing the JSON string in this manner is used to help prevent JSON
* Hijacking. The prefix renders the string syntactically invalid as a
* script so that it cannot be hijacked. This prefix does not affect the
* evaluation of JSON, but if JSON validation is performed on the string,
* the prefix would need to be ignored.
*/
public void setPrefixJson(boolean prefixJson) {
this._prefixJson = prefixJson;
}
#Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return canRead(mediaType);
}
#Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
return canRead(mediaType);
}
#Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return canWrite(mediaType);
}
#Override
protected boolean supports(Class<?> clazz) {
// should not be called, since we override canRead/Write instead
throw new UnsupportedOperationException();
}
/**
* Generic types will be processed here.
*/
#Override
public Object read(Type type, Class<?> contextClass,
HttpInputMessage inputMessage)
throws HttpMessageNotReadableException, IOException {
setType(type);
return readInternal(null, inputMessage);
}
#Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
Reader json = new InputStreamReader(inputMessage.getBody(),
getCharset(inputMessage.getHeaders()));
try {
Type typeOfT = getType();
if (typeOfT != null) {
return _gson.fromJson(json, typeOfT);
} else {
return _gson.fromJson(json, clazz);
}
} catch (JsonSyntaxException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: "
+ ex.getMessage(), ex);
} catch (JsonIOException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: "
+ ex.getMessage(), ex);
} catch (JsonParseException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: "
+ ex.getMessage(), ex);
} finally {
setType(null);
}
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
OutputStreamWriter writer = new OutputStreamWriter(
outputMessage.getBody(), getCharset(outputMessage.getHeaders()));
try {
if (this._prefixJson) {
writer.append("{} && ");
}
Type typeOfSrc = getType();
if (typeOfSrc != null) {
_gson.toJson(o, typeOfSrc, writer);
} else {
_gson.toJson(o, writer);
}
writer.close();
} catch (JsonIOException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: "
+ ex.getMessage(), ex);
}
}
// helpers
private Charset getCharset(HttpHeaders headers) {
if (headers != null && headers.getContentType() != null
&& headers.getContentType().getCharSet() != null) {
return headers.getContentType().getCharSet();
}
return DEFAULT_CHARSET;
}
}
Get request method in SocialGraphUI.java. There is object test and method allNodes, which returns list of objects of class Node and allEdges returns list of objects of class Edge.
#RequestMapping(value = "/", method = RequestMethod.GET)
public String getNodesAndEdges(ModelMap model) {
model.addAttribute("nodes", test.allNodes);
model.addAttribute("edges", test.allEdges);
return "index";
}
I get these error messages:
type Exception report
message Servlet.init() for servlet SocialGraphUI threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet SocialGraphUI threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcUriComponentsContributor': Cannot create inner bean '(inner bean)#1043cc94' of type [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter] while setting bean property 'handlerAdapter'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1043cc94': Cannot create inner bean 'com.example.converter.GsonMessageConverter#0' of type [com.example.converter.GsonMessageConverter] while setting bean property 'messageConverters' with key [0]; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.converter.GsonMessageConverter] for bean with name 'com.example.converter.GsonMessageConverter#0' defined in ServletContext resource [/WEB-INF/SocialGraphUI-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.example.converter.GsonMessageConverter
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:290)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1043cc94': Cannot create inner bean 'com.example.converter.GsonMessageConverter#0' of type [com.example.converter.GsonMessageConverter] while setting bean property 'messageConverters' with key [0]; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.converter.GsonMessageConverter] for bean with name 'com.example.converter.GsonMessageConverter#0' defined in ServletContext resource [/WEB-INF/SocialGraphUI-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.example.converter.GsonMessageConverter
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:290)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:122)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:359)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.converter.GsonMessageConverter] for bean with name 'com.example.converter.GsonMessageConverter#0' defined in ServletContext resource [/WEB-INF/SocialGraphUI-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.example.converter.GsonMessageConverter
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1325)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:122)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:359)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
java.lang.ClassNotFoundException: com.example.converter.GsonMessageConverter
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
org.springframework.util.ClassUtils.forName(ClassUtils.java:247)
org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)
org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1346)
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1317)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:122)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:359)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.
The main problem here could be the duplicate mvc:annotation-driven declaration.
But anyway, Spring 4.1 introduced Gson support so that makes it way easier for you to achieve this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cz.ario.socialgraphui.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.GsonHttpMessageConverter" />
<!-- other HttpMessageConverters you need here -->
<!-- Also: why adding Jackson's MessageConverter? Gson should pick JSON serialization in this case -->
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:resources mapping="/scripts/**" location="/scripts/" />
<mvc:resources mapping="/styles/**" location="/styles/" />
</beans>
Same thing with a JavaConfig example:
#Configuration
#EnableWebMvc
#ComponentScan("cz.ario.socialgraphui.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new GsonHttpMessageConverter());
// ...
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/");
registry.addResourceHandler("/styles/**").addResourceLocations("/styles/");
}
}
Note: you should (almost) never use versioned XSDs in your XML configuration files - see this SO question for more details.
Related
Hello i want create datatables javaspring mvc
i'm follow this link
http://www.opencodez.com/java/datatable-with-spring-boot.htm
but i have problem
Error creating bean with name 'dataTableColumnSpecs' defined in file [tomcat_path\DataTableColumnSpecs.class]
Error Log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataTableColumnSpecs' defined in file [local_tomcat\hris\WEB-INF\classes\org\hris\datatables\DataTableColumnSpecs.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hris.datatables.DataTableColumnSpecs]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1101)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
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:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hris.datatables.DataTableColumnSpecs]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
... 29 more
Caused by: java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
... 30 more
Oct 16, 2017 11:20:58 AM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [spring] in web application [] threw load() exception
java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
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:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataTableColumnSpecs' defined in file [local_tomcat\hris\WEB-INF\classes\org\hris\datatables\DataTableColumnSpecs.class]: Instantiation of be failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hris.datatables.DataTableColumnSpecs]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1101)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
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:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:828)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hris.datatables.DataTableColumnSpecs]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
... 36 more
Caused by: java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
... 37 more
Oct 16, 2017 11:21:00 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet spring
java.lang.NoSuchMethodException: org.hris.datatables.DataTableColumnSpecs.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
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:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:828)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<!-- context:component-scan base-package="org.bkn.hris.controller" / -->
<context:component-scan base-package="org.bkn.hris">
<context:include-filter type="regex" expression="org.bkn.hris.*"/>
</context:component-scan>
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename" value="classpath:messages" />
<beans:property name="defaultEncoding" value="UTF-8" />
</beans:bean>
<beans:bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<beans:property name="defaultLocale" value="en" />
<beans:property name="cookieName" value="myAppLocaleCookie"></beans:property>
<beans:property name="cookieMaxAge" value="3600"></beans:property>
</beans:bean>
</beans:beans>
DataTableColumnSpecs.java
package org.bkn.hris.datatables;
import javax.servlet.http.HttpServletRequest;
public class DataTableColumnSpecs {
/** The index. */
private int index;
/** The data. */
private String data;
/** The name. */
private String name;
/** The searchable. */
private boolean searchable;
/** The orderable. */
private boolean orderable;
/** The search. */
private String search;
/** The regex. */
private boolean regex;
/** The sort dir. */
private String sortDir;
/**
* Instantiates a new data table column specs.
*
* #param request the request
* #param i the i
*/
public DataTableColumnSpecs(HttpServletRequest request, int i) {
this.setIndex(i);
prepareColumnSpecs(request, i);
}
/**
* Gets the data.
*
* #return the data
*/
public String getData() {
return data;
}
/**
* Sets the data.
*
* #param data the data to set
*/
public void setData(String data) {
this.data = data;
}
/**
* Gets the name.
*
* #return the name
*/
public String getName() {
return name;
}
/**
* Sets the name.
*
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Checks if is searchable.
*
* #return the searchable
*/
public boolean isSearchable() {
return searchable;
}
/**
* Sets the searchable.
*
* #param searchable the searchable to set
*/
public void setSearchable(boolean searchable) {
this.searchable = searchable;
}
/**
* Checks if is orderable.
*
* #return the orderable
*/
public boolean isOrderable() {
return orderable;
}
/**
* Sets the orderable.
*
* #param orderable the orderable to set
*/
public void setOrderable(boolean orderable) {
this.orderable = orderable;
}
/**
* Gets the search.
*
* #return the search
*/
public String getSearch() {
return search;
}
/**
* Sets the search.
*
* #param search the search to set
*/
public void setSearch(String search) {
this.search = search;
}
/**
* Checks if is regex.
*
* #return the regex
*/
public boolean isRegex() {
return regex;
}
/**
* Sets the regex.
*
* #param regex the regex to set
*/
public void setRegex(boolean regex) {
this.regex = regex;
}
/**
* Gets the sort dir.
*
* #return the sortDir
*/
public String getSortDir() {
return sortDir;
}
/**
* Sets the sort dir.
*
* #param sortDir the sortDir to set
*/
public void setSortDir(String sortDir) {
this.sortDir = (null != sortDir) ? sortDir.toUpperCase() : sortDir;
}
/**
* Gets the index.
*
* #return the index
*/
public int getIndex() {
return index;
}
/**
* Sets the index.
*
* #param index the index to set
*/
public void setIndex(int index) {
this.index = index;
}
/**
* Prepare column specs.
*
* #param request the request
* #param i the i
*/
private void prepareColumnSpecs(HttpServletRequest request, int i) {
this.setData(request.getParameter("columns["+ i +"][data]"));
this.setName(request.getParameter("columns["+ i +"][name]"));
this.setOrderable(Boolean.valueOf(request.getParameter("columns["+ i +"][orderable]")));
this.setRegex(Boolean.valueOf(request.getParameter("columns["+ i +"][search][regex]")));
this.setSearch(request.getParameter("columns["+ i +"][search][value]"));
this.setSearchable(Boolean.valueOf(request.getParameter("columns["+ i +"][searchable]")));
int sortableCol = Integer.parseInt(request.getParameter("order[0][column]"));
String sortDir = request.getParameter("order[0][dir]");
if(i == sortableCol) {
this.setSortDir(sortDir);
}
}
}
Your problem is evident in this stack trace row:
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.hris.datatables.DataTableColumnSpecs]:
No default constructor found; nested exception is java.lang.NoSuchMethodException
This happens because your context:component-scan is scanning your classes and found DataTableColumnSpecs that haven't the default constructor, alias constructor with no parameters. Normally you don't need to add explicitly the default constructor unless you specify another constructor with parameters, that is your case.
What you need to do is to add the default constructor to your DataTableColumnSpecs, as following:
/**
* Default/empty constructor
*/
public DataTableColumnSpecs() {
super();
}
I am having a problem with spring , when launching the app in the server I have this error message, please help Thanks in advance!!.
Error Message
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'procesarController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zonagifts.web.service.TransaccionService com.zonagifts.web.controller.ProcesarController.transaccionService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TransaccionService' defined in file [C:\Users\Adolfo\Desktop\ZonacardEstableciemiento\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Webzonagifts\WEB-INF\classes\com\zonagifts\web\service\TransaccionServiceImpl.class]: Post-processing failed of bean type [class com.zonagifts.web.service.TransaccionServiceImpl] failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.zonagifts.web.service.TransaccionServiceImpl] for resource metadata: could not find class that it depends on
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779) [catalina.jar:7.0.27]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273) [catalina.jar:7.0.27]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.27]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566) [catalina.jar:7.0.27]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556) [catalina.jar:7.0.27]
at java.util.concurrent.FutureTask.run(FutureTask.java:262) [na:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_75]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_75]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_75]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zonagifts.web.service.TransaccionService com.zonagifts.web.controller.ProcesarController.transaccionService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TransaccionService' defined in file [C:\Users\Adolfo\Desktop\ZonacardEstableciemiento\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Webzonagifts\WEB-INF\classes\com\zonagifts\web\service\TransaccionServiceImpl.class]: Post-processing failed of bean type [class com.zonagifts.web.service.TransaccionServiceImpl] failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [com.zonagifts.web.service.TransaccionServiceImpl] for resource metadata: could not find class that it depends on
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 22 common frames omitted
My servlet.xml is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<context:component-scan base-package="com.zonagifts.web" >
<context:include-filter type="aspectj" expression="com.zonagifts.*"/>
</context:component-scan>
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" cache-period="604800" />
<mvc:view-controller path="/error" view-name="error" />
<bean id="viewResolver1" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="prefix" value="/WEB-INF/jsp/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="es" />
</bean>
</beans>
My controller is
package com.zonagifts.web.controller;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zonagifts.web.domain.ResponseServicio;
import com.zonagifts.web.domain.Usuario;
import com.zonagifts.web.service.TransaccionService;
import com.zonagifts.web.util.Constantes;
#Controller
#RequestMapping("procesar")
public class ProcesarController {
#Autowired
private TransaccionService transaccionService;
private static Logger log = Logger.getLogger(LoginController.class);
#RequestMapping(value="activar",method=RequestMethod.POST)
public #ResponseBody ResponseServicio activarTarjeta(HttpSession sesion,String numeroTarjeta){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.activarTarjeta(numeroTarjeta, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
}
return responseServicio;
}
#RequestMapping(value="anular",method=RequestMethod.POST)
public #ResponseBody ResponseServicio anular(HttpSession sesion,String numeroTarjeta){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.anularTarjeta(numeroTarjeta, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
}
return responseServicio;
}
#RequestMapping(value="consumo",method=RequestMethod.POST)
public #ResponseBody ResponseServicio consumo(HttpSession sesion,String numeroTarjeta,String codigoSeguridad,String monto){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.consumirSaldo(numeroTarjeta, codigoSeguridad, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), monto, Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
//responseServicio.setIdTransaccion(respuesta[3]);
}
return responseServicio;
}
#RequestMapping(value="saldo",method=RequestMethod.POST)
public #ResponseBody ResponseServicio saldo(HttpSession sesion,String numeroTarjeta){
ResponseServicio responseServicio=new ResponseServicio();
Usuario usuario=(Usuario) sesion.getAttribute(Constantes.SESION_USUARIO_ZONA_CARDS);
if(usuario != null){
String [] respuesta=transaccionService.consultarSaldo(numeroTarjeta, usuario.getCodigoComercio(), usuario.getCodigoTerminal(), Constantes.TRANSACCION);
responseServicio.setRespuesta(respuesta[0]);
responseServicio.setCodigoOperacion(respuesta[1]);
responseServicio.setMensaje(respuesta[2]);
}
return responseServicio;
}
}
TransactionServiceImpl
package com.zonagifts.web.service;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.tempuri.GiftCardsSoapProxy;
import com.zonagifts.api.util.Util;
import com.zonagifts.web.controller.LoginController;
#Service
public class TransaccionServiceImpl implements TransaccionService {
private static GiftCardsSoapProxy giftCardsSoapProxy;
private static Logger log = Logger.getLogger(LoginController.class);
public String[] activarTarjeta(String numeroTarjeta, String codigoComercio,
String codigoTerminal, String idTransaccion) {
String token =tarjeta.concat(comercio).concat(terminal).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.activar_tarjeta(numeroTarjeta.trim(),
codigoComercio.trim(), codigoTerminal.trim(),
idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
return res ;
}
public String[] anularTarjeta(String numeroTarjeta, String codigoComercio,
String codigoTerminal, String idTransaccion) {
String token =tarjeta.concat(comercio).concat(terminal).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.anular_tarjeta(numeroTarjeta.trim(),
codigoComercio.trim(), codigoTerminal.trim(),
idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
//guardarTransaccionBD(tx);
return res ;
}
public String[] consumirSaldo(String numeroTarjeta, String codigoSeguridad,
String codigoComercio, String codigoTerminal, String montoConsumir,
String idTransaccion) {
String token =tarjeta.concat(codSeguridad).concat(comercio).concat(terminal).concat(monto).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.consumir_tarjeta(numeroTarjeta.trim(),
codigoSeguridad.trim(),codigoComercio.trim(),
codigoTerminal.trim(),montoConsumir.trim(), idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
return res ;
}
public String[] consultarSaldo(String numeroTarjeta, String codigoComercio,
String codigoTerminal, String idTransaccion) {
String token =tarjeta.concat(comercio).concat(terminal).concat(transaccion).concat(pass);
Object response=null;
try {
giftCardsSoapProxy=new GiftCardsSoapProxy();
response = giftCardsSoapProxy.consultar_saldo(numeroTarjeta.trim(),
codigoComercio.trim(), codigoTerminal.trim(),
idTransaccion.trim(), token);
} catch (RemoteException e) {
e.printStackTrace();
}
String[] res = (String[]) response;
return res ;
}
}
TransaccionService
package com.zonagifts.web.service;
public interface TransaccionService {
String[] activarTarjeta(String numeroTarjeta,String codigoComercio,String codigoTerminal,String idTransaccion);
String[] anularTarjeta(String numeroTarjeta,String codigoComercio,String codigoTerminal,String idTransaccion);
String[] consumirSaldo(String numeroTarjeta,String codigoSeguridad,String codigoComercio,String codigoTerminal,String montoConsumir,String idTransaccion);
String[] consultarSaldo(String numeroTarjeta,String codigoComercio,String codigoTerminal,String idTransaccion);
}
So the final exception that you get is the following:
java.lang.IllegalStateException: Failed to introspect bean class [com.zonagifts.web.service.TransaccionServiceImpl] for resource metadata: could not find class that it depends on
Looking at your TransaccionServiceImpl class, there are a few things that could be missing from your class path...
org.tempuri.GiftCardsSoapProxy
com.zonagifts.web.controller.LoginController
There are others, but these are the two that give me the most pause.
Could you verify that these two files (or their jar files) are in your deployed classpath?
After looking at your My servlet.xml I found that you didn't have the context:annotation-config tag. As you are using annotations to wire your beans you need to have this tag in your xml.
<context:annotation-config></context:annotation-config>
As there is a single Implementation for the interface and the component scanning is turned on, I don't think you will need to qualify the bean. But if app doesn't work even after adding the context:annotation-config tag, try to qualify the bean. You can qualify as follows
Annotate the TransaccionServiceImpl class with #service("transaccionServiceImplBean") and when you wire it in ProcesarController provide the qualifier as below
#Autowired
#Qualifier("transaccionServiceImplBean")
private TransaccionService transaccionService;
I am trying to build my first Spring MVC project, I've been reading alot of tutorials, watching video etc...but I am facing this problem:
The error :
HTTP Status 500 - Servlet.init() for servlet springDispatcherServlet threw exception
type Exception report
message Servlet.init() for servlet springDispatcherServlet threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet springDispatcherServlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'equipementController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.etraveldoo.service.EquipementService com.etraveldoo.controllers.EquipementController.equipementService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.data.mongodb.core.MongoTemplate] for bean with name 'equipementmongoTemplate' defined in ServletContext resource [/WEB-INF/springDispatcherServlet-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.data.mongodb.core.MongoTemplate
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.etraveldoo.service.EquipementService com.etraveldoo.controllers.EquipementController.equipementService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.data.mongodb.core.MongoTemplate] for bean with name 'equipementmongoTemplate' defined in ServletContext resource [/WEB-INF/springDispatcherServlet-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.data.mongodb.core.MongoTemplate
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.data.mongodb.core.MongoTemplate] for bean with name 'equipementmongoTemplate' defined in ServletContext resource [/WEB-INF/springDispatcherServlet-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.data.mongodb.core.MongoTemplate
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1352)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1445)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:445)
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:423)
org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:220)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1177)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
java.lang.ClassNotFoundException: org.springframework.data.mongodb.core.MongoTemplate
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1397)
org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1344)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:628)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:597)
org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1445)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:445)
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:423)
org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:220)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1177)
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
SpringDispatcherServet-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.etraveldoo.controllers" />
<mvc:annotation-driven/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="equipementmongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="eTraveldoo" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/equipementmessages"></property>
<property name="cacheSeconds" value="1"/>
</bean>
EquipementController:
package com.etraveldoo.controllers;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.etraveldoo.models.Equipement;
import com.etraveldoo.service.EquipementService;
#Controller
public class EquipementController {
#Autowired
private EquipementService equipementService;
#InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, "createdDate", new CustomDateEditor(dateFormat, false));
}
#RequestMapping(value="/add.html", method= RequestMethod.GET)
public ModelAndView getindexPage() {
ModelAndView model = new ModelAndView("AddEquipement");
return model;
}
#ModelAttribute
public void CommonObject(Model model) {
model.addAttribute("Message", "eTraveldoo Exploitation Interface");
}
#RequestMapping(value="/newEquipement.html", method = RequestMethod.POST)
public ModelAndView submitEq( #Valid #ModelAttribute("equipement") Equipement equipement, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AddEquipement");
return model;
}
ModelAndView model = new ModelAndView("SucessPage");
return model;
}
}
EquipementService :
package com.etraveldoo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.etraveldoo.models.Equipement;
public class EquipementService {
#Autowired
private MongoTemplate equipementmongoTemplate;
public void saveEquipement(Equipement equipement) {
if (!equipementmongoTemplate.collectionExists(Equipement.class)) {
equipementmongoTemplate.createCollection(Equipement.class);
}
equipementmongoTemplate.insert(equipement, "equipementTable");
}
public List<Equipement> listEquipement() {
return equipementmongoTemplate.findAll(Equipement.class, "equipementTabel");
}
}
And the Model :
package com.etraveldoo.models;
import java.util.Date;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;
#Document(collection="Equipements")
public class Equipement {
#Id
private String id;
private String name;
private String os;
private String ip;
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date createdDate;
private ArrayList<String> functions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public ArrayList<String> getFunctions() {
return functions;
}
public void setFunctions(ArrayList<String> functions) {
this.functions = functions;
}
#Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
#Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
#Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
#Autowired
public Equipement(String id, String name, String os, String ip, Date createdDate, ArrayList<String> functions) {
super();
this.id = id;
this.name = name;
this.os = os;
this.ip = ip;
this.createdDate = createdDate;
this.functions = functions;
}
}
This is the relevant information from the error:
Error creating bean with name 'equipementController': Injection of autowired dependencies failed;
Could not autowire field: private com.etraveldoo.service.EquipementService com.etraveldoo.controllers.EquipementController.equipementService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.data.mongodb.core.MongoTemplate] for bean with name 'equipementmongoTemplate' defined in ServletContext resource [/WEB-INF/springDispatcherServlet-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.data.mongodb.core.MongoTemplate
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
And the most significant portion is the ClassNotFoundException for the class org.springframework.data.mongodb.core.MongoTemplate
It appears your Spring Data MongoDb dependencies are not properly setup.
The reference for setting up in Maven or Spring Boot via Gradle can be found here:
https://github.com/spring-projects/spring-data-mongodb
Im previously wrote the code which save data from form in spring and it worked fine.
Now i have tried to wrote the code which get data from android client and save it in mysql database. but in result i have a problem
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'signupController' defined in file
Also i dont understand why i have such problem if i have in dispatcher-servet
<context:component-scan base-package="com.dubovskiyM.mvc"/>
<context:annotation-config/>
Or can this problem cause because controller and repository situated in differends folders. but in one package com.dubovskiyM.mvc?
My files
Controller
#Controller
#RequestMapping("/test")
public class SignupController {
private Reg_repository reg_repository;
#Autowired
public SignupController(Reg_repository reg_repository) {
this.reg_repository = reg_repository;
}
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody String signupm(#RequestBody String s){
Gson gson = new Gson();
Signup signup = gson.fromJson(s,Signup.class);
return signup.getLogin();}
}
Dispatcher
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:beans="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.dubovskiyM.mvc"/>
<context:annotation-config/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan"
value="com.dubovskiyM.mvc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.current_session_context_class">
org.springframework.orm.hibernate4.SpringSessionContext
</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/andr_spring" />
<property name="username" value="root" />
<property name="password" value="181987" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Repository
#Repository
public class Reg_repository implements ResumeDAO {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional(readOnly = true)
public Signup find(String login) {
log.trace("Find UserDAO with id = " + login + " ...");
Signup signup = (Signup) sessionFactory.getCurrentSession().get(Signup.class,login);
if (signup != null) {
log.trace("Find UserDAO with id: " + signup.getLogin());
}
return signup;
}
#Override
public Set<Signup> findAll() {
return null;
}
#Override
#Transactional(readOnly = false)
public void save(Signup signup) {
// if(find(signup.getLogin()) == null) {
sessionFactory.getCurrentSession().save(signup);
// }
}
#Override
#Transactional(readOnly = false)
public void update(Signup signup) {
if(find(signup.getLogin()) != null) {
sessionFactory.getCurrentSession().update(signup);
}
}
#Override
#Transactional(readOnly = false)
public void remove(Signup signup) {
if(find(signup.getLogin()) != null) {
sessionFactory.getCurrentSession().delete(signup);
}
}
}
Trace
javax.servlet.ServletException: Servlet.init() for servlet mvc-dispatcher threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'signupController' defined in file [D:\Server\And_server\And_server\target\And_server\WEB-INF\classes\com\dubovskiyM\mvc\controller\SignupController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.dubovskiyM.mvc.controller.SignupController]: Illegal arguments for constructor; nested exception is java.lang.IllegalArgumentException: argument type mismatch
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.dubovskiyM.mvc.controller.SignupController]: Illegal arguments for constructor; nested exception is java.lang.IllegalArgumentException: argument type mismatch
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:159)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:121)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
java.lang.IllegalArgumentException: argument type mismatch
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:526)
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:121)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
"Only one annotated constructor per-class can be marked as required, but multiple non-required constructors can be annotated. In that case, each is considered among the candidates and Spring uses the greediest constructor whose dependencies can be satisfied, that is the constructor that has the largest number of arguments." per Spring doc
So remove the default constructor and try.
I'm new to Spring MVC and Hibernate and I'm having a problem with my session configurations. I have done this by using the hibernate. What I want to do now is that the sessionFactory will be autowired in the DAO.
This is the application-context.xml -----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- Map simple view name such as "test" into /WEB-INF/test.jsp -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/jsp" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Scan classpath for annotations (eg: #Service, #Repository etc) -->
<context:component-scan base-package="com.nutsaboutcandywebproject.controller"/>
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_nutsaboutcandy"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<list>
<value>com.nutsaboutcandywebproject.model</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
This is the full stacktrace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartController' defined in file [C:\Users\Jeremy Marvin\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NutsAboutCandyWebProject\WEB-INF\classes\com\nutsaboutcandywebproject\controller\ShoppingCartController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
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: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.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
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.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 34 more
Caused by: java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 36 more
Apr 04, 2014 1:30:44 AM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shoppingCartController' defined in file [C:\Users\Jeremy Marvin\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NutsAboutCandyWebProject\WEB-INF\classes\com\nutsaboutcandywebproject\controller\ShoppingCartController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
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: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.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
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.BeanInstantiationException: Could not instantiate bean class [com.nutsaboutcandywebproject.controller.ShoppingCartController]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
... 34 more
Caused by: java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
... 36 more
Apr 04, 2014 1:30:44 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet appServlet
java.lang.NullPointerException
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getCurrentSession(SQLProductsDataAccess.java:24)
at com.nutsaboutcandywebproject.dao.SQLProductsDataAccess.getInventory(SQLProductsDataAccess.java:35)
at com.nutsaboutcandywebproject.service.ServiceFacadeImpl.getAllProducts(ServiceFacadeImpl.java:140)
at com.nutsaboutcandywebproject.controller.ShoppingCartController.<init>(ShoppingCartController.java:35)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)
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: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.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This is the code for the DAO
package com.nutsaboutcandywebproject.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import com.nutsaboutcandywebproject.model.Category;
import com.nutsaboutcandywebproject.model.Inventory;
import com.nutsaboutcandywebproject.model.Product;
import com.nutsaboutcandywebproject.model.ProductTypes;
public class SQLProductsDataAccess implements IProductsDataAccess {
#Autowired
SessionFactory sessionFactory;
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public Inventory getInventory()
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from Product";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
#SuppressWarnings("unchecked")
List<Product> productsList = (List<Product>) query.list();
Inventory inventory = new Inventory();
inventory.setProducts(productsList);
transaction.commit();
session.close();
return inventory;
}
public Product getProductById(Integer id) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
Query hqlQuery = session.createQuery("from Product WHERE id = :id");
hqlQuery.setParameter("id", id);
System.out.println("Query created...");
List<?> productList = hqlQuery.list();
Product product = (Product) productList.get(0);
transaction.commit();
session.close();
return product;
}
public List<Category> getCategoryName()
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from Category";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
List<Category> categoryList = query.list();
transaction.commit();
session.close();
return categoryList;
}
#Override
public Integer addStock(Integer id)
{
Product product = getProductById(id);
int quantity = product.getQuantityInStock() + 1000;
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "UPDATE Product set quantityInStock = :quantity"
+ " where id = :id";
Query query = session.createQuery(sqlQuery);
query.setParameter("quantity", quantity);
query.setParameter("id", id);
query.executeUpdate();
transaction.commit();
session.close();
return quantity;
}
#Override
public List<ProductTypes> getTypeName() {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "from ProductTypes";
Query query = session.createQuery(sqlQuery);
System.out.println("Query created...");
List<ProductTypes> typeList = query.list();
transaction.commit();
session.close();
return typeList;
}
#Override
public void updateProduct(Integer updatedQuantity, Integer productId) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
String sqlQuery = "UPDATE Product set quantityInStock = :quantity"
+ " where id = :id";
Query query = session.createQuery(sqlQuery);
query.setParameter("quantity", updatedQuantity);
query.setParameter("id", productId);
System.out.println("Query created...");
query.executeUpdate();
transaction.commit();
session.close();
}
#Override
public Integer deleteProduct(Integer productId)
{
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("delete Product where id = :id");
query.setParameter("id",productId);
int result = query.executeUpdate();
transaction.commit();
session.close();
return result;
}
}
ShoppingCartController
package com.nutsaboutcandywebproject.controller;
#SessionAttributes(value = {"customerSession","cartSession"})
#Controller
public class ShoppingCartController {
private ServiceFacade facade = new ServiceFacadeImpl();
private NACExceptions exceptionsNAC = new NACExceptions();
private List<Product> productsList = facade.getAllProducts();
private List<Category> categoryList = facade.getCategory();
private List<ProductTypes> typeList = facade.getType();
private List<Sizes> sizeList = facade.getAllSizes();
private List<ProductPriceMatrix> priceMatrixList = facade.getProductPriceMatrices();
private List<String> exceptionList = new ArrayList<String>();
#RequestMapping(value = "/cart", method = RequestMethod.POST)
public String doShop(Model model, #RequestParam("smallSize") String[] small,
#RequestParam("mediumSize") String[] medium ,#RequestParam("largeSize") String[] large)
{
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession();
List<ShoppingCart> cartList = new ArrayList<ShoppingCart>();
boolean isCartEmpty = true;
if(session.getAttribute("cartSession")!=null){
cartList = (List<ShoppingCart>) session.getAttribute("cartSession");
isCartEmpty = false;
}
for(int index=0; index<productsList.size();index++){
int numberOfSmall = 0;
int numberOfMedium = 0;
int numberOfLarge = 0;
Integer productId = productsList.get(index).getId();
Sizes size = priceMatrixList.get(index).getSize();
Product product = facade.getSingleProduct(productId);
try{
exceptionsNAC.numberCheck(small[index]);
exceptionsNAC.numberCheck(medium[index]);
exceptionsNAC.numberCheck(large[index]);
exceptionsNAC.checkValues(small[index]);
exceptionsNAC.checkValues(medium[index]);
exceptionsNAC.checkValues(large[index]);
numberOfSmall = Integer.parseInt(small[index]);
numberOfMedium = Integer.parseInt(medium[index]);
numberOfLarge = Integer.parseInt(large[index]);
}catch(ProductException e){
exceptionList.add(e.getMessage());
}
User user = (User) session.getAttribute(("customerSession"));
if(small[index] != null && numberOfSmall!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(50,numberOfSmall,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfSmall);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
if(medium[index] != null && numberOfMedium!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(100,numberOfMedium,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfMedium);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
if(large[index] != null && numberOfLarge!=0){
try {
if(exceptionsNAC.getRemainingQuantityInStock(150,numberOfLarge,product.getId())){
ShoppingCart cart = new ShoppingCart(0,user,product,size,numberOfLarge);
cartList.add(cart);
}
} catch (ProductException e) {
exceptionList.add(e.getMessage());
}
}
}
if(isCartEmpty){
session.setAttribute("cartSession", cartList);
}
model.addAttribute("cartSession", cartList);
model.addAttribute("productsList", productsList);
model.addAttribute("categoryList", categoryList);
model.addAttribute("typeList", typeList);
model.addAttribute("sizeList", sizeList);
model.addAttribute("priceMatrixList", priceMatrixList);
model.addAttribute("exception", exceptionList);
return "/ShoppingCart";
}
}
You are missing "dao" package in your component-scan config:
<context:component-scan base-package="com.nutsaboutcandywebproject.controller"/>
<context:component-scan base-package="com.nutsaboutcandywebproject.dao"/>
Also, DAO class must have #Repository annotation in order to use it as an autowired component.
Your DAO and service objects need to be beans under Spring control. By instantiating them like this:
private ServiceFacade facade = new ServiceFacadeImpl();
Spring never gets to inject your dependencies and wire everything up, hence the NPE. Add the following to your XML file
<context:component-scan base-package="com.nutsaboutcandywebproject.dao"/>
<context:component-scan base-package="com.nutsaboutcandywebproject.service"/>
and make sure your DAO is marked with #Repository or #Component, and your services as #Service or #Component. And change the instantiation of facade to
#Autowired
private ServiceFacade facade;
Since there was no scan for the DAO package, you almost certainly have to do the same in ServiceFacadeImpl and its IProductsDataAccess field.
Update: Besides this, you're accessing beans which haven't been initialised yet, e.g.
private List<Product> productsList = facade.getAllProducts();
At that point in time, i.e. during object instantiation, Spring hasn't finished creating your DAOs, Hibernate session factory, etc. You can only access these beans and set your fields when Spring has finished initialising and injecting the dependencies. To do that, put the code in an initialisation method marked with #PostConstruct:
#Controller
public class ShoppingCartController {
#Autowired
private ServiceFacade facade;;
private NACExceptions exceptionsNAC = new NACExceptions();
private List<Product> productsList;
private List<Category> categoryList;
private List<ProductTypes> typeList;
private List<Sizes> sizeList;
private List<ProductPriceMatrix> priceMatrixList;
private List<String> exceptionList = new ArrayList<String>();
#PostConstruct
public void someInitializationMethod() {
productsList = facade.getAllProducts();
categoryList = facade.getCategory();
typeList = facade.getType();
sizeList = facade.getAllSizes();
priceMatrixList = facade.getProductPriceMatrices();
}
....
Add few more lines like this - in order to initiate the bean along with the datasource
<bean id="shoppingCartController" class="point.it.to.implementation.class">
<property name="mySessionFactory" ref="mySessionFactory"/>
</bean>
You can even try using #Autowired annotation, by simplying creating the setter method for it.