我搭建一个Spring MVC 环境。controller中加上@Controller注解
[code="java"]
@Controller
public class Login {
private IUserService userService;
public IUserService getUserService() {
return userService;
}
public void setUserService(IUserService userService) {
this.userService = userService;
}
@RequestMapping("login.html")
public String login(HttpServletRequest request, HttpServletResponse response, ModelAndView view){
System.out.println("handle the login.html");
System.out.println(userService.getUserByCustId("000001031234").getUserMail());
return "index";
}
}
[/code]
在spring的配置文件中配置注解扫描等。同时配置
[code="java"]
[/code]
注入userService。
问题来了:
如果不加这个注入项目可以正常运行,如果加了这个注入。提示异常
[code="java"]
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot map handler 'loginController' to URL path [/login.html]: There is already handler of type [class com.sdemo.controller.Login] mapped.
[/code]
请问该怎么办呢?问题出在哪里?注解和注入不能并存么?
userService有没配置或注解啊
@Service
private IUserService userService;
去掉配置
[code="java"]
[/code]
将注解进行到底! :arrow:
这句日志你没有看懂吗?
Cannot map handler 'loginController' to URL path [/login.html]: There is already handler of type [class com.sdemo.controller.Login] mapped.
答案就在这里。
sky_sz 正解。我前端时间做过。
@Autowired
private IUserService userService;
其他答案都是答非所谓,题主的意思是既要用component-scan来读取并映射@controller类的@RequestMapping,又要用标签注入一些属性。
先分析原因,由于在component-scan扫描Login时默认生成的id是类名首字母小写,也就是“login”,而bean里配置的id是loginController(如果不写默认是类全路径#定义次数,即com.sdemo.controller.Login#0),也就是spring容器其实是[b]生成了两个Login对象![/b],由于带有@controller注解,所以每个对象都会执行@RequestMapping映射,所以就报错了,提示路径已被之前的对象映射过了。
解决方案有两种:
1. 把里的id改为和component-scan生成的一致即可,也就是
[code="xml"]
[/code]
这样不仅注入了内容,而且只映射一次。
最后建议各位,遇到问题时应该注意仔细看错误日志,然后思考并反复调试配置来找到解决方案。