对于一个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>
答案 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实例的组件