Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Spring annotated controller necessarily need a default constructor

I have a spring controller that uses annotations. I gave this controller a constructor that takes two arguments. I want both ways of initializing the controller: constructor injection and setter injection.

@Controller("viewQuestionController")
@RequestMapping("/public/viewQuestions")
public class ViewQuestionController
{
    @Resource(name="questionService")
    private QuestionService questionService;

   /*public ViewQuestionController()
 {
    int i=0;
    i++;
 } 
   */   

public ViewQuestionController(@Qualifier("questionService") QuestionService questionService)
{
    this.questionService = questionService;
}

@Resource(name="questionService")
public void setQuestionService(QuestionService questionService)
{
    this.questionService = questionService;
}
}   

When I uncomment the default constructor, the controller is initiated correctly. However, if I don't, I get a BeanInstantiationException, No default constructor found; nested exception is java.lang.NoSuchMethodException. So, is my configuration for the annotated constructor wrong or does a completely annotated controller in spring always need a default constructor?

like image 474
Abhijeet Kashnia Avatar asked Feb 15 '26 03:02

Abhijeet Kashnia


2 Answers

If you want to configure constructor injection via annotations, you need to put the corresponding annotation on the constructor. I'm not sure how it can be done with @Resource, but @Autowired and @Inject support it:

@Autowired
public ViewQuestionController(@Qualifier("questionService") QuestionService questionService) 

or

@Inject
public ViewQuestionController(@Named("questionService") QuestionService questionService) 
like image 193
axtavt Avatar answered Feb 18 '26 05:02

axtavt


I think Controller beans need a default constructor as they are initialized by the framework but there is no way to tell the framework hot to provide the dependency.

On second thought why not you autowire your question service and Spring will take care of it. The following code should be good

 @Controller("viewQuestionController")
 @RequestMapping("/public/viewQuestions")
 public class ViewQuestionController
 {
       @Autowired
       private QuestionService questionService;

       //Not providing any constructor would also be fine
       public ViewQuestionController(){}

questionService will be initialized properly by Spring

like image 39
lalit Avatar answered Feb 18 '26 03:02

lalit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!