这是我的控制器课
@Controller
public class HomeController{
@RequestMapping("/")
public String home(MyTest test){
test.draw();
return "homePage";
}
}
在将MyTest(Interface)作为参数传递给home方法时,Spring不会注入其实现类,而是引发异常
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/spring-mvc-demo] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface com.managers.MyTest] with root cause
java.lang.NoSuchMethodException: com.managers.MyTest.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:209)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:84)
但是在直接传递实现类即MyTestImpl时,它可以正常工作。
@RequestMapping("/")
public String home(MyTestImpl test){
test.draw();
return "homePage";
}
在接口的情况下,能否请您在此说明异常的原因。下面是MyTest实现类
@Component
public class MyTestImpl implements MyTest{
@Override
public void draw() {
System.out.println("inside test");
}
}
Spring.xml
<context:component-scan base-package="com.controllers,com.ManagerImpl" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
互换的青春
喵喔喔
烙印99
随时随地看视频慕课网APP
相关分类