1

Spring MVCを使用して、私はこのControllerクラスを持っています:

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;
    // more code and a setter to loginService
}

LoginServiceはインターフェースであり、その唯一の実装はLoginServiceImpl次のとおりです。

public class LoginServiceImpl implements LoginService {
    //
}

私のproject-name-servlet.xmlファイルはこれです:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">   
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="loginService" class="my.example.service.impl.LoginServiceImpl" />
    <bean class="my.example.controller.LoginController" />
</beans>

問題は、loginServiceコントローラーに注入されていないことです。以下のようにXMLファイルでインジェクションを指定すると、次のように機能します。

    <bean id="loginService"
        class="may.example.service.impl.LoginServiceImpl" />
    <bean class="my.example.controller.LoginController">
        <property name="loginService" ref="loginService"></property>
    </bean>

なぜこれが起こるのですか?インターフェイスタイプのインジェクションポイントにインジェクションされるのは、実装されているBeanだけではありませんか?

4

2 に答える 2

1

自動配線を機能させるには、 AutowiredAnnotationBeanPostProcessorを追加する必要があります。これはデフォルトでbyTypeであるため、loginServiceをLoginControllerに挿入するために明示的に何もする必要はありません。リンクにあるように、<context:annotation-config/>またはを配置<context:component-scan/>してAutowiredAnnotationBeanPostProcessorを自動的に登録できます。

于 2012-07-04T00:44:29.893 に答える
0

私にうまくいった解決策は、autowireタイプを次のように定義することでしたbyType

    <bean id="loginService"
        class="my.example.service.impl.LoginServiceImpl"
            autowire="byType" />
    <bean class="my.example.controller.LoginController"
            autowire="byType" />

また、@Autowiredアノテーションを削除しました。

于 2012-07-03T22:00:38.690 に答える