Skip to content
Advertisement

Spring MVC web application: No default constructor found

Project ZIP: http://goo.gl/ddhLg5


Spring web app cannot be executed giving HTTP Status 500 error. It also writes out that No default constructor found for DSLR but in fact there is a default constructor. Maybe it has to do with application context or the way my beans declared? What is the reason my application cannot start?

DSLR:

 package main.java.com.springapp.mvc.model;

    public class DSLR {

    public DSLR() {
    }
    public void init() {}

    private int dslrId;
    private String model;
    private int price;
    private String description;

    public int getDslrId() {
        return dslrId;
    }

    public void setDslrId(int dslrId) {
        this.dslrId = dslrId;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "DSLR [dslr=" + dslrId + ", model=" + model
                + ", price=" + price+ ", description=" + description+"]";
    }
}

web.xml

<web-app version="2.4"
                   xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring MVC Application</display-name>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

DSLRServletController-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"
           xsi:schemaLocation="
       http://www.springframework.org/schema/beans     
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="main.java.com.springapp.mvc" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>


    <bean name="s" class="main.java.com.springapp.mvc.controller.DSLRServletController">
        <property  name="dslrDAO" ref="dslrDAO" />
        <property  name="DSLR" ref="DSLR" />
    </bean>
    <bean id="dslrDAO" class="main.java.com.springapp.mvc.dao.DSLRDAO">

    </bean>
    <bean id="DSLR" class="main.java.com.springapp.mvc.model.DSLR">

    </bean>


</beans>

mvc-dispatcher-servlet.xml

<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"
       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">

    <context:component-scan base-package="main.java.com.springapp.mvc"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

ERROR:

HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lmain.java.com.springapp.mvc.model.DSLR;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lmain.java.com.springapp.mvc.model.DSLR;.<init>()

type Exception report

message Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lmain.java.com.springapp.mvc.model.DSLR;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lmain.java.com.springapp.mvc.model.DSLR;.<init>()

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lmain.java.com.springapp.mvc.model.DSLR;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lmain.java.com.springapp.mvc.model.DSLR;.<init>()
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:927)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lmain.java.com.springapp.mvc.model.DSLR;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lmain.java.com.springapp.mvc.model.DSLR;.<init>()
    org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:108)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveModelAttribute(HandlerMethodInvoker.java:770)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:363)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:439)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:427)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

java.lang.NoSuchMethodException: [Lmain.java.com.springapp.mvc.model.DSLR;.<init>()
    java.lang.Class.getConstructor0(Class.java:2810)
    java.lang.Class.getDeclaredConstructor(Class.java:2053)
    org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveModelAttribute(HandlerMethodInvoker.java:770)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:363)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:439)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:427)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.52 logs.

Main controller class:

package main.java.com.springapp.mvc.controller;

import main.java.com.springapp.mvc.dao.DSLRDAO;
import main.java.com.springapp.mvc.model.DSLR;
import main.java.com.springapp.mvc.pckg.DSLRForm;
import main.java.com.springapp.mvc.pckg.DSLRValidaor;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;

@Controller
public class DSLRServletController extends HttpServlet  {
    static Logger logger = Logger.getLogger(DSLRServletController.class);

    private DSLR DSLR;
    private DSLRDAO dslrDAO;
    private DSLR dslr;

   /* request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=utf-8");
    List list = getActions(request, response);
    response.setContentType("text/html; charset=UTF-8");*/

    //@Autowired   ???
    public DSLRServletController() {
        this.dslrDAO = new DSLRDAO();
    }

    public void init() {logger.error("DSLRServlet.init(): just started"); }
    /*
            /s                                    GET
            /s?id=1                               GET
            /s?action=save                        POST
            /dslrservice?id=1&tm=<timestamp>      GET
     */
@RequestMapping(value = "/s", method = RequestMethod.GET)
public String showHTMLResponse(@ModelAttribute("dslrs") DSLR dslrs[],
                               @ModelAttribute("dslr") DSLR dslr,
                               @ModelAttribute("dslrErrors") HashMap dslrErrors,
                               @ModelAttribute ("dslrform") DSLRForm dslrForm,
                               @RequestParam("id") String paramId,
                               @RequestParam("action") String paramAction,
                               Model model){

    if(paramId == null || paramId.equals("")){
        //show_all_dslrs
        dslrs = getAllDslrs();    // DSLR adslrs[] -> to MODEL;
       return "dslrs";
    }else{
        //show_this_dslr;
        HashMap<String,Object> dslrHashMap = getDSLRById(paramId);
        dslr = (DSLR) dslrHashMap.get("dslr");
        dslrForm = (DSLRForm)dslrHashMap.get("dslrForm");
        dslrErrors = (HashMap)dslrHashMap.get("dslrErrors");

            if(dslr != null){
//                getServletConfig().getServletContext().getRequestDispatcher("/dslr.jsp").forward(request, response);
                return "dslr";
            }

            else{
                return "error";
            }


    }
}

@RequestMapping(value = "/s", method = RequestMethod.POST)
public String showHTMLResponsePOST(@ModelAttribute("dslrs") DSLR dslrs[],
                               @ModelAttribute("dslrErrors") HashMap<?,?> dslrErrors,
                               @ModelAttribute ("dslrform") DSLRForm dslrForm,

                               @RequestParam("id") String paramId,
                               @RequestParam("action") String paramAction,
                               @RequestParam("dslr_model") String paramModel,
                               @RequestParam("price") String paramPrice,
                               @RequestParam("description") String paramDescription,
                               Model model){
    int iStatusCode = 0;
    if(paramAction.equals("save") )
        iStatusCode = saveDSLR(paramId, paramModel, paramPrice, paramDescription, dslrErrors, dslrForm);    // POST

    return "dslrs";

}

    private int saveDSLR(String paramId,
                         String paramModel,
                         String paramPrice,
                         String paramDescription,
                         HashMap<?,?> context_dslrErrors,
                         DSLRForm context_dslrForm
                         ) {
        int byte0 = 1;
        try {

            DSLRValidaor dslrValidaor = new DSLRValidaor();

            DSLRForm dslrForm = new DSLRForm();
            dslrForm.setDslrId(paramId);
            dslrForm.setModel(paramModel);
            dslrForm.setPrice(paramPrice);
            dslrForm.setDescription(paramDescription);

            HashMap hashmap = dslrValidaor.Validate(dslrForm);
            if(hashmap.size() > 0) {
                context_dslrForm = dslrForm;
                context_dslrErrors = hashmap;
                byte0 = -1;
            } else{
                DSLRDAO planedao = new DSLRDAO();
                DSLR dslr = new DSLR();
                dslr.setDslrId(Integer.parseInt(paramId));
                dslr.setModel(paramModel);
                dslr.setPrice(Integer.parseInt(paramPrice));
                dslr.setDescription(paramDescription);
                planedao.update(dslr);
            }
        }
        catch(Exception exception)
        {
            logger.error((new StringBuilder()).append("DSLRServlet.saveDSLR():").append(exception.getMessage()).toString());
            byte0 = -1;
        }
        return byte0;

    }

    private DSLR[] getAllDslrs(){
        DSLR adslrs[] = null;
        try
        {
            DSLRDAO DSLRDAO = new DSLRDAO();
            adslrs = (DSLR[])DSLRDAO.findAll();
        }
        catch(Exception exception)
        {
            logger.error((new StringBuilder()).append("PlaneServlet.getAllPlanes():").append(exception.getMessage()).toString());
        }
//        request.setAttribute("dslrs", adslrs);
        return adslrs;
    }

    private HashMap<String, Object> getDSLRById(String s)
    {
        HashMap<String,Object> map = new HashMap<String, Object>();

        DSLR dslr = null;
        try {
            int i = Integer.parseInt(s);
            DSLRDAO DSLRDAO = new DSLRDAO();
            dslr = (DSLR)DSLRDAO.findById(i);

            DSLRForm dslrForm = new DSLRForm();
            dslrForm.setDslrId(Integer.toString(dslr.getDslrId()));
            dslrForm.setModel(dslr.getModel());
            dslrForm.setPrice(Integer.toString(dslr.getPrice()));
            dslrForm.setDescription(dslr.getDescription());


            map.put("dslr", dslr);
            map.put("dslrform", dslrForm);
            map.put("dslrErrors", new HashMap());
        }
        catch(Exception exception)
        {
            logger.error((new StringBuilder()).append("DSLRServlet.getDSLRById():").append(exception.getMessage()).toString());
        }
        return map;
    }

    public void setDslrDAO(DSLRDAO dslrDAO) {
        this.dslrDAO = dslrDAO;
    }

    public DSLRDAO getDslrDAO() {
        return dslrDAO;
    }

    public void setDSLR(main.java.com.springapp.mvc.model.DSLR DSLR) {
        dslr = DSLR;
    }

    public main.java.com.springapp.mvc.model.DSLR getDSLR() {
        return dslr;
    }
}

UPDATE1:

new mvc-dispatcher-servlet.xml:

<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"
       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">

    <context:component-scan base-package="main.java.com.springapp.mvc" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

And @Autowired was put in DSLRServletController:

@Autowired
    public DSLRServletController() {
        this.dslrDAO = new DSLRDAO();
    }

Errors:

exception

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.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:744)
root cause

java.lang.IllegalStateException: Autowired annotation requires at least one argument: public main.java.com.springapp.mvc.controller.DSLRServletController()
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:243)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:976)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
    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:607)
    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:647)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    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.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:744)

For some reason 2 errors appeared. What should be changed to set up project correctly?


UPDATE3

the new mvc-dispatcher-servlet.xml:

<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"
       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">

    <context:component-scan base-package="main.java.com.springapp.mvc" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean id="DSLR" class="main.java.com.springapp.mvc.model.DSLR" />
</beans>

Apart from @Autowired added in UPDATE1, another one is added (in DSLRServletController):

@Autowired
    public void setDSLR(DSLR DSLR) {
        dslr = DSLR;
    }

UPDATE4:

Back to the original errors : Could not instantiate bean class [[Lmain.java.com.springapp.mvc.model.DSLR;]

I am confused. What’s wrong?

Advertisement

Answer

Inside your controller method , you have used a parameter as array like below

@ModelAttribute("dslrs") DSLR dslrs[]

so use collection like list instead

@ModelAttribute("dslrs") ArrayList<DSLR> dslrs
3 People found this is helpful
Advertisement