【问题标题】:Unable to autowire attributes in package无法自动装配包中的属性
【发布时间】:2015-07-25 11:03:20
【问题描述】:

由于某种原因,在我的配置包中,我无法自动装配字段,而在我的控制器包中,似乎没有任何问题。

例如:

servlet-context.xml

<context:component-scan base-package="service, controller, config" />

root-context.xml(也尝试在这里添加服务)

<context:component-scan base-package="security" />

这不起作用:配置包内的设置类。我收到一个空指针错误。

@Component
public class Setup { //inside the config package
    @Autowired
    private UserService userService; //null pointer error
    /*..other stuff */
}

这确实有效:控制器包内的控制器:

@Controller
@RequestMapping(value="/contact")
public class ContactController { //inside the controller package
    @Autowired
    private UserService userService; //this works
    /*..other stuff..*/
}

为什么它适用于控制器包而不适用于配置包?

【问题讨论】:

    标签: spring spring-mvc dependency-injection spring-annotations


    【解决方案1】:

    发生这种情况的原因可能是 @ServiceUserService 在“config”或“”两个包中的任何一个中都不可见控制器”我假设您还需要对包含服务的包进行组件扫描:

    <context:component-scan base-package="service" />
    

    编辑:

    通常您应该记住,如果 Bean/Component 不在扫描的上下文中,它在注入时将始终为 null(自动装配) .

    编辑 2:

    所以你可能已经看到 Spring 有两种类型的上下文,ApplicationContextServletContext。如果您在 ServletContext 中扫描一个 bean,它将只能从 Controllers 访问(或者正如名称从 servlet 中所指出的那样),但 bean 是由 ApplicationContext 也可以从 Services 或其他 Components 访问,并且任何 servlet 都可以访问此处扫描的 bean,而无需在 servlet 上下文中扫描它们。

    在您的情况下,您应该具有以下设置:

    servlet-context.xml 中:

    <context:component-scan base-package="controller" />
    

    applicationContext.xmlroot-context.xml 中(我假设您已经在 web.xml 中这样引用它)

    <context:component-scan base-package="config, security, services" />
    

    下图展示了 Spring 的上下文层次结构:

    【讨论】:

    • 嗨,不幸的是,这仍然不起作用。我感觉这可能是因为我有 2 个 xml:root-context.xml 和 servlet-context.xml。我更新了我的帖子。
    • 感谢博格丹的回答。不幸的是,这也不起作用。 userService 在 config.Setup 类中仍然为空。如果有什么我可以提供更清晰的信息,请告诉我。
    • @Moody 在linkedin 或我的博客上给我写私信,我会帮你修复它,然后我们会在这里发布正确的解决方案
    【解决方案2】:

    尝试使用此配置:

    <context:component-scan base-package="config,controller" />
    

    【讨论】:

    • 您可以在此处找到有关基于注释的 bean 配置的更多详细信息:stackoverflow.com/questions/7414794/…
    • 感谢您的评论,不幸的是它不起作用。我也尝试按照您给我的帖子(尽管他们使用单独的 setter 方法并将自动装配的方法放在它们上面),但它仍然没有用。
    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多