@Autowired是什么时候为bean调用的?

时间:2014-06-24 10:55:28

标签: java spring

对于一个bean:

@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之前被调用?如果是这样,我怎么能在输入方法showView之前配置Spring连接myBean?

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

2 个答案:

答案 0 :(得分:0)

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

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

其中your.package.path是您拥有控制器类的路径。

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

答案 1 :(得分:0)

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

通常,@RequestMapping@Controller注释(扩展@Component注释)一起手动进行,以便它被视为Spring bean和(根据javadoc

  

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