2012-07-08 122 views
1

我正在创建一个Spring MVC Web应用程序,我喜欢使用控制器等组件的自动发现。Spring组件扫描不起作用?映射的URL返回404

在我的应用程序上下文文件,我把下面的标签

<context:component-scan base-package="com.example" /> 

有一个存在于com.example.springmvc.controller

@Controller 
public class AccountController { 

    @RequestMapping("/account.html") 
    public ModelMap showAccount() throws Exception { 

     ModelMap modelMap = new ModelMap(); 
     modelMap.addAttribute("someText", "This is an account"); 

     return modelMap; 
    } 

    @RequestMapping("/account.html") 
    public ModelMap showAccount(@RequestParam("accountId") int accountId) throws Exception  { 

     ModelMap modelMap = new ModelMap(); 
     modelMap.addAttribute("someText", String.format("This is an account with id %d", accountId)); 

     return modelMap; 
    } 

} 

当我转到本地主机测试控制器: 8080/account.html我得到一个404,所以我必须忘记一些东西。

当我创建一个自定义映射在我的MVC配置文件,如下所示,比它的工作。至少,那么我会在控制器中遇到一些有关隐形方法的错误,但这是另一个问题。至少它找到了控制器。

<bean name="/account.html" class="com.example.springmvc.controller.AccountController"/> 

我不想在XML创建我的映射,我想用注释的URL映射。你能告诉我我在这里忘了什么吗?

回答

3

要启用基于注解配置扫描,添加以下Spring配置:

<mvc:annotation-driven /> 
+0

感谢阿龙,这个工程。 此外,要annyone阅读:确保你有一个日志框架,如log4j设置,以便您可以在应用程序启动时看到发生了什么。我在启动我的应用程序时遇到了“SEVERE:Error listenerStart”错误,并且在配置log4j后我才发现问题所在。看起来,我第一次在我的applicationcontext文件中没有正确的xsi:schemaLocation =值,所以没有正确加载mvc XSD。其次,我的控制器中有一个错误的方法映射,导致应用程序无法正常启动。 – Julius 2012-07-09 00:22:33