代码之家  ›  专栏  ›  技术社区  ›  user373201

spring mvc annotation@Inject不工作

  •  0
  • user373201  · 技术社区  · 15 年前

    我的app-servlet.xml中有以下内容

    <mvc:annotation-driven />
    
    <context:component-scan base-package="com.merc.myProject.web.controllers"/>
    <context:component-scan base-package="com.merc.myProject.web.forms"/>
    

    我的controller包中的任何内容都会被注入,但是forms包中的相同内容总是空的。

    我的表格看起来像这样

    public class SelectDatesForm {
    
        @Inject IUserService userService;
        .....
    }
    

    我的控制器是这样的

    @Controller
    public class SelectDates {
    
       @Inject IUserService userService;
    
       .....
    }
    

    有人请帮忙

    2 回复  |  直到 15 年前
        1
  •  1
  •   axtavt    15 年前

    我想你的 SelectDatesForm 手动实例化 new 而不是从Spring上下文中获取。在本例中,它不是Spring bean,因此也不是依赖注入的主题。

    通常不需要将依赖项注入到手动创建的对象中。如果你真的需要这样做,你有几个选择:

    • 宣布 选择日期窗体 作为一个原型作用域bean,并从Spring上下文获取它的一个新实例,而不是使用 新的 :

      @Component @Scope("prototype")
      public class SelectDatesForm { ... }
      

      当你需要获得一个新的实例时:

      SelectDatesForm newForm = applicationContext.getBean(SelectDatesForm.class);
      

      但是,这种方法将您的代码与Spring的 ApplicationContext .

    • 如果您无法控制 选择日期窗体 (即它发生在您的代码之外),您可以使用 @Configurable

    • 此外,您还可以手动简化使用创建的对象的自动连接 新的 :

      SelectDatesForm newForm = new SelectDatesForm();
      applicationContext.getAutowireCapableBeanFactory().autowireBean(newForm);
      
        2
  •  4
  •   skaffman    15 年前

    <context:component-scan> 查找用以下内容注释的类 @Component , @Controller , @Service ,依此类推,并将其配置为bean。如果这些类具有 @Inject @Resource ,然后这些也将被处理。

    但是,如果您的类没有注释开始,那么 @注入 不会被处理。是这样的 SelectDatesForm . 如果你用 @组成部分 ,它应该被捡起来。

    不过,我在这里要小心一点——表单通常不适合SpringBean,因为它们往往是被丢弃的、暂时的对象。