使用 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不应该注入接口类型的注入点吗?