Spring MVC基于XML配置手动声明Bean时@Autowired注入为null问题求助
问题原因
@Autowired注解需要 Spring 对应的后置处理器支持才能生效。<context:component-scan>标签在扫描注册带注解的Bean之外,默认会自动开启注解配置支持,所以用组件扫描时注入功能正常。- 纯手动声明Bean时没有配置
<context:annotation-config/>,Spring不会主动处理@Autowired注解,导致注入的对象为null。 - 你原有配置中手动声明Bean的注释块错误包裹了
</beans>结束标签,启用手动配置时如果没修正这个问题,会导致XML配置文件结构非法,配置不生效。
解决步骤
修改servlet-context.xml配置,移除<context:component-scan>标签,添加<context:annotation-config/>,正确声明Bean即可,示例配置如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/> <!-- 开启注解配置支持,处理@Autowired等注解 --> <context:annotation-config/> <!-- 手动声明Bean --> <bean id = "restCtrl" class = "org.Test.RestCtrl"></bean> <bean id = "person" class="org.Test.Person"> <property name="name" value="ABC"></property> <property name="age" value = "22"></property> </bean> </beans>
内容的提问来源于stack exchange,提问作者mohit tiwari
相关产品推荐
相关产品推荐

