You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring注解自动装配Address属性为null,加context标签报错求助

Spring @Autowired自动装配为null及context:annotation-config异常问题解决

问题现象

  1. 使用@Autowired注解为Emp类的address属性自动装配时,控制台输出该属性值为null
  2. 在XML配置文件中添加<context:annotation-config>标签后触发解析异常

核心问题分析

  1. XML命名空间配置错误:原配置中xmlns:context和xmlns:p的属性值多了多余的=符号,导致Spring无法正确识别命名空间,从而触发<context:annotation-config>解析异常。
  2. 未开启注解自动装配支持: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:48:17