【问题标题】:When is @Autowired invoked for a bean?何时为 bean 调用 @Autowired?
【发布时间】:2014-08-14 14:35:59
【问题描述】:

对于一个豆子:

@Autowired
private MyBean myBean;

这个 bean 之前是否自动装配:

@RequestMapping("VIEW")
public String showView { 
  //myBean is null here
}

我问的原因是 myBean 设置为 null。但是对于其他具有

@RenderMapping("NORMAL")
public String renderNormal{ 
  //myBean is not null here
}

myBean 似乎已正确自动装配。

@RequestMapping("VIEW") 是否导致 myBean 未连接或在 Spring 自动连接 myBean 之前被调用?如果是这样,我如何配置 Spring 在进入方法 showView 之前连接 myBean?

更新:我在 Spring 上下文文件中缺少 &lt;context:annotation-config /&gt;,这个问题提供了一些有关其使用的详细信息:Difference between <context:annotation-config> vs <context:component-scan>

【问题讨论】:

  • 你的 showView 方法是在一个带有注解 @Controller 的类中吗?
  • 您需要展示更多与 Spring 相关的代码,以便我们弄清楚发生了什么
  • 您似乎在混合 Spring MVC 和 Spring bean 的概念。

标签: java spring


【解决方案1】:

单独的 @RequestMapping 注释不会使您的类成为 Spring bean。

通常,@RequestMapping@Controller 注释(它扩展了 @Component 注释)一起使用,因此它被视为 Spring bean 并且(根据 javadoc)到

表示一个接收 HttpServletRequest 和 HttpServletResponse 实例的组件

【讨论】:

    【解决方案2】:

    假设你的 showView 方法在一个用 @Controller 注释的类中,你应该有

      <context:component-scan base-package="your.package.path" />
    

    your.package.path 是控制器类所在的路径。

    另请参阅以下链接,例如:Auto component scan example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多