1、报错
Could not autowire. No beans of ‘HttpServletResponse’ type found.
2、原因
spring团队只让HttpServletRequest自动装配功能,排除HttpServletResponse(故意给排除了!真der!!)。spring团队倡导把reqeust、response与其他实例分开。
3、解释
servlet是服务器创建的,所以不属于IOC管理,没法自动注入。sevlet至少也需要服务器启动时,才会创建,而在编写代码时,肯定是不存在滴。
4、解决
1)该注解不进行检查,服务器启动之后会实例化servlet,这样就不会报错了
@Autowired(required = false)
private HttpServletResponse response;
2)将其作为方法参数
public void test(HttpServletResponse response){
}
3)将@Autowired改为@Resource
- 两个注解的区别是一个是@Autowired是Spring,@Resource是J2EE的。
- 使用@Resource能减少Spring耦合度。
- @AutoWried按by type自动注入,而@Resource默认按byName自动注入。
- @Resource的查询注入顺序是,去Bean中查找Name,如果查不到就去查Class,其次再从属性去查找,如果我们定义的类中有相同的Name可能会报错,因为查询到了多个。
————————————————
参考链接:BUG——@Autowired HttpServletResponse报错(Could not autowire. No beans of ‘HttpServletResponse’ type fo)_Today_He的博客-优快云博客
解决Could not autowire.No beans of ‘ ‘ type found_luoluo95的博客-优快云博客