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

这是我的控制器课


@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>


互换的青春
浏览 292回答 3
3回答

喵喔喔

您所做的方式是完全错误的。这是一个工作代码,@Controllerpublic class HomeController{&nbsp; private final MyTest test;&nbsp; &nbsp;@Autowired&nbsp; &nbsp;public HomeController(MyTest test) {&nbsp; &nbsp; &nbsp; this.test = test;&nbsp; &nbsp;}&nbsp; &nbsp;@RequestMapping("/")&nbsp; &nbsp;public String home(){&nbsp; &nbsp; &nbsp; test.draw();&nbsp; &nbsp; &nbsp; return "homePage";&nbsp; &nbsp;}}@RequestMapping应该/将要注释的方法的论点以Pathvariable或RequestParams的形式出现,或者只是HttpServletRequest对象本身的形式出现。这不是您自动装配实例的方式。依赖注入在构造函数,字段和接口级别上工作。不在方法参数级别。希望它清除。

烙印99

您所做的是正确的,除了需要告诉Spring如何反序列化您的接口(即预期使用哪种具体的类实现。如果在MyTest实现中使用JSON序列化(通常是Spring的默认设置),请添加以下注释&nbsp; &nbsp; @JsonDeserialize(as=MyTestImpl.class)&nbsp; &nbsp; public interface MyTest&nbsp; {&nbsp; &nbsp; ...另外,假设您使用的是Post方法,请将Controller更改为:@PostMapping(value = "/",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; produces = MediaType.APPLICATION_JSON_UTF8_VALUE)&nbsp; &nbsp; public String home(MyTest test){&nbsp; &nbsp; &nbsp; &nbsp; test.draw();&nbsp; &nbsp; &nbsp; &nbsp; return "homePage";&nbsp; &nbsp; }(“产生”参数当然可以是text / html或您返回的任何东西)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java