java.lang.IllegalStateException: Autowired annotation requires at least one argument

StackOverflow https://stackoverflow.com/questions/23683282

  •  23-07-2023
  •  | 
  •  

Question

Cannot Autowire and run Spring web application.

Error:

java.lang.IllegalStateException: Autowired annotation requires at least one argument: public main.java.com.springapp.mvc.controller.DSLRServletController()

DSLRServletController:

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   {
    static Logger logger = Logger.getLogger(DSLRServletController.class);


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



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

    public void init() {logger.error("DSLRServlet.init(): just started"); }

@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; HOW?
       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){

                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;
    }
    @Autowired
    public void setDslrDAO(DSLRDAO dslrDAO) {
        this.dslrDAO = dslrDAO;
    }

    public DSLRDAO getDslrDAO() {
        return dslrDAO;
    }
    @Autowired
    public void setDSLR(DSLR DSLR) {
        dslr = DSLR;
    }

    public DSLR getDSLR() {
        return dslr;
    }
}

Why @Autowired annotation returns error? How to fix it?

Était-ce utile?

La solution 2

The constructor isnt a valid setter method or instance variable

@Autowired
private DSLRDAO dslrDAO;

Autres conseils

In addition to reimeus answer, you can't use @Autowired on a default constructor.

It's often considered better to autowire the constructor rather than a field.

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

I was facing this same issue and found the root cause, which is different than the original question asked, but may help someone for sure.

We were using Lombok jar to generate default code like Getters/Setters, similarly we were using Lombok annotation to generate a Constructor for the Required Argument and mark it with @Autowired behind the scene.

 @RequiredArgsConstructor(onConstructor = @__(@Autowired))    
 public class MyClass {
  private MyDependency myDependency;
}

The issue which was causing the problem was a missing final keyword while defining the dependency. @RequiredArgsConstructor identifies the required argument as the one which are marked final and must be populated during construction.

Another annotation which could have been used is @AllArgsConstructor (this will create a constructor for all the dependencies so final is not really needed)

So, the correct solution to resolve the said error is to use final

@RequiredArgsConstructor(onConstructor = @__(@Autowired))    
 public class MyClass {
  private final MyDependency myDependency;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top