Spring 注释控制器是否一定需要默认构造函数 [英] Does a Spring annotated controller necessarily need a default constructor
问题描述
我有一个使用注解的弹簧控制器.我给了这个控制器一个带有两个参数的构造函数.我想要两种初始化控制器的方式:构造函数注入和 setter 注入.
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;
}
}
当我取消对默认构造函数的注释时,控制器会正确启动.但是,如果我不这样做,我会得到一个 BeanInstantiationException, No default constructor found;嵌套异常是 java.lang.NoSuchMethodException.那么,我对带注释的构造函数的配置是错误的还是在 spring 中完全注释的控制器总是需要一个默认的构造函数?
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?
推荐答案
如果想通过注解配置构造函数注入,需要在构造函数上加上相应的注解.我不确定如何使用 @Resource
完成它,但是 @Autowired
和 @Inject
支持它:
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)
或
@Inject
public ViewQuestionController(@Named("questionService") QuestionService questionService)
这篇关于Spring 注释控制器是否一定需要默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!