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

Spring Boot XML定义中如何获取ApplicationContext 无注解实现方法

Spring XML配置下获取ApplicationContext的实现方案

完全使用XML配置无需注解的场景下,有两种常用实现方式,等效于你给出的@Autowired注入写法:

方案1:直接在XML中配置依赖注入

Spring容器默认会将自身的ApplicationContext实例以applicationContext为名称注册为内置Bean,你只需给需要上下文的类添加对应setter方法,再在XML中配置属性注入即可:

  1. 业务类示例代码
public class YourBusinessBean {
    private ApplicationContext appContext;

    // XML注入需要调用setter方法,必须提供
    public void setAppContext(ApplicationContext appContext) {
        this.appContext = appContext;
    }

    // 后续业务逻辑可直接使用appContext
}
  1. 对应XML配置
<bean class="com.yourproject.package.YourBusinessBean">
    <property name="appContext" ref="applicationContext"/>
</bean>

方案2:实现ApplicationContextAware接口(官方推荐)

这是Spring框架原生提供的上下文获取标准接口,无需任何额外配置,Spring容器启动时会自动识别接口实现类并注入上下文:

  1. 业务类示例代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class YourBusinessBean implements ApplicationContextAware {
    private ApplicationContext appContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        // Spring自动回调该方法完成上下文赋值
        this.appContext = applicationContext;
    }

    // 后续业务逻辑可直接使用appContext
}
  1. 对应XML配置
<!-- 无需配置属性注入,Spring自动识别接口完成注入 -->
<bean class="com.yourproject.package.YourBusinessBean"/>

注意事项

  • 两种方案都完全适配纯XML配置项目,不需要引入任何注解
  • Spring Boot场景下只要通过@ImportResource加载你的XML配置文件,两种方案都可正常生效
  • 方案2不依赖内置Bean的固定名称,兼容性更强,更推荐使用

内容的提问来源于stack exchange,提问作者Mohammad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:45:03