Spring 组件中的 MVC 自动装配为空

Spring MVC Autowired null in Component

我的组件是:

package com.netpc.recruitment.models.user;
@Component
public class UserAuth {
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private IUserDAO userDAO;
}

在控制器中创建对象时,变量 httpSessionuserDAOnulluserDAO 配置正确,在我的 com.netpc.recruitment.controllers.IndexController class @Controller.

中运行良好

我的web.xml

<beans ......>
    <context:component-scan base-package="com.netpc.recruitment.controllers" />
    <bean id="userDAO" class="com.netpc.recruitment.models.user.JDBCUserDAO">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

有什么问题吗?为什么是 null

您的组件扫描仅在 "com.netpc.recruitment.controllers" 上扫描。还应扫描包 com.netpc.recruitment.models.user。 web.xml 的变化:

  <context:component-scan base-package="com.netpc.recruitment.controllers" />

对此:

  <context:component-scan base-package="com.netpc.recruitment.controllers, com.netpc.recruitment.models.user" />

希望这对你有用!