Spring注解自动装配Address属性为null,加context标签报错求助
Spring @Autowired自动装配为null及context:annotation-config异常问题解决
问题现象
- 使用@Autowired注解为Emp类的address属性自动装配时,控制台输出该属性值为null
- 在XML配置文件中添加
<context:annotation-config>标签后触发解析异常
核心问题分析
- XML命名空间配置错误:原配置中
xmlns:context和xmlns:p的属性值多了多余的=符号,导致Spring无法正确识别命名空间,从而触发<context:annotation-config>解析异常。 - 未开启注解自动装配支持:Spring默认不会主动处理@Autowired等注解,必须通过
<context:annotation-config>开启注解处理器,否则@Autowired不生效,address属性无法被注入。
解决方案
1. 修复XML配置文件
修正命名空间的错误声明,并添加<context:annotation-config>开启注解支持:
<?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: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"> <bean class="com.springcore.auto.wire.annotation.Address" name="tempaddress" > <property name="street" value="Temp street" /> <property name="city" value="Mysore" /> </bean> <bean class="com.springcore.auto.wire.annotation.Emp" name="emp1" /> <!-- 开启Spring注解自动装配支持 --> <context:annotation-config/> </beans>
2. 可选:指定装配名称(如果需要)
@Autowired默认按类型装配,当前容器中仅存在一个Address类型的bean,因此无需额外配置即可完成注入。若后续存在多个同类型bean,可结合@Qualifier指定目标bean名称:
@Autowired @Qualifier("tempaddress") private Address address;
3. 验证结果
修改完成后运行Test类,控制台应输出:
Emp [address=Address [street=Temp street, city=Mysore]]
注:Emp类同时存在带参构造器和无参构造器,@Autowired默认优先通过构造器注入,此时会打印
Setting value using constructor;若需强制使用setter注入,可将@Autowired注解移至setAddress方法上。
内容的提问来源于stack exchange,提问作者Manoj P
相关产品推荐
相关产品推荐

