开发者

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 d开发者_如何学JAVAoes a completely annotated controller in spring always need a default constructor?


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) 


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜