为了账号安全,请及时绑定邮箱和手机立即绑定

当给定接口作为参数时,依赖注入不起作用

当给定接口作为参数时,依赖注入不起作用

互换的青春 2021-04-16 22:27:08
这是我的控制器课@Controllerpublic 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 causejava.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实现类@Componentpublic 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>
查看完整描述

3 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

您所做的方式是完全错误的。这是一个工作代码,


@Controller

public class HomeController{

  private final MyTest test;


   @Autowired

   public HomeController(MyTest test) {

      this.test = test;

   }


   @RequestMapping("/")

   public String home(){

      test.draw();

      return "homePage";

   }

}

@RequestMapping应该/将要注释的方法的论点以Pathvariable或RequestParams的形式出现,或者只是HttpServletRequest对象本身的形式出现。这不是您自动装配实例的方式。


依赖注入在构造函数,字段和接口级别上工作。不在方法参数级别。希望它清除。


查看完整回答
反对 回复 2021-04-28
?
烙印99

TA贡献1829条经验 获得超13个赞

您所做的是正确的,除了需要告诉Spring如何反序列化您的接口(即预期使用哪种具体的类实现。如果在MyTest实现中使用JSON序列化(通常是Spring的默认设置),请添加以下注释


    @JsonDeserialize(as=MyTestImpl.class)

    public interface MyTest  {

    ...

另外,假设您使用的是Post方法,请将Controller更改为:


@PostMapping(value = "/",

            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,

            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

    public String home(MyTest test){

        test.draw();

        return "homePage";

    }

(“产生”参数当然可以是text / html或您返回的任何东西)


查看完整回答
反对 回复 2021-04-28
  • 3 回答
  • 0 关注
  • 291 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号