【Spring】Spring容器对象的那些事

【Spring】Spring容器对象的那些事

开篇词:

最近开发时,遇到一个场景,需要运行时获取用户的环境信息,借此跟大家唠唠spring容器对象

附上获取环境信息的代码示例

bash 复制代码
 @Autowired
private ApplicationContext context;

public void printAllBeans() {
    String[] beanNames = context.getBeanDefinitionNames();
    Arrays.stream(beanNames).forEach(System.out::println);
}

public void getEnvironmentProperty() {
    Environment env = context.getEnvironment();
    String value = env.getProperty("xxx.config");
}

干货篇:

一.获取spring容器对象有哪些常用方式

1.实现BeanFactoryAware接口
bash 复制代码
@Service
public  class OrderService implements BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void add() {
        Order order = (Order) beanFactory.getBean("order");
    }
}

实现BeanFactoryAware接口,然后重写setBeanFactory方法,就能从该方法中获取到spring容器对象。

2.实现ApplicationContextAware接口
bash 复制代码
@Service
public  class PersonService2 implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void add() {
        Order order = (Order) applicationContext.getBean("order");
    }

}

实现ApplicationContextAware接口,然后重写setApplicationContext方法,也能从该方法中获取到spring容器对象。

3.实现ApplicationListener接口
bash 复制代码
@Service
public  class PersonService3 implements ApplicationListener<ContextRefreshedEvent> {
    private ApplicationContext applicationContext;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        applicationContext = event.getApplicationContext();
    }

    public void add() {
        Order order = (Order)applicationContext.getBean("order");
    }

}

需要注意的是,实现ApplicationListener接口,接收的泛型是ContextRefreshedEvent类,然后重写onApplicationEvent方法,也能从该方法中获取到spring容器对象。

Spring的Aware接口是一组特殊的标记接口(空接口),它们本身不包含任何方法,但通过实现这些接口,Spring容器会在初始化Bean时自动注入对应的依赖对象。这种设计模式被称为回调机制,它为Bean提供了与容器底层能力交互的通道,常用于需要突破依赖注入限制或实现容器级功能扩展的场景

二.那还有其他什么场景会用到spring容器对象?

未被spring托管代码,访问spring bean

当部分代码无法被Spring管理(如第三方库的回调类),但需要访问Spring Bean时。

示例:

bash 复制代码
java
public class LegacyCallback implements SomeThirdPartyCallback {
    private ApplicationContext context;

    public LegacyCallback(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void onEvent() {
        MyService service = context.getBean(MyService.class);
        service.handleEvent();
    }
}
单元测试

在单元测试或集成测试中,手动创建或获取ApplicationContext以模拟容器环境。

示例(使用Spring TestContext框架):

bash 复制代码
java
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class MyTest {
    @Autowired
    private ApplicationContext context;

    @Test
    public void testBeanExists() {
        assertTrue(context.containsBean("myService"));
    }
}

手动创建容器(不推荐生产使用):

bash 复制代码
java
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService service = context.getBean(MyService.class);

我是杰叔叔,一名沪漂的码农,下期再会!

相关推荐
钱六两2 小时前
#3、SpringAI 接入deepSeek大模型(喂饭版)
java·spring boot·ai编程
Suhan422 小时前
IDEA 设置启动参数和环境变量
spring boot·spring·编辑器·idea
songroom2 小时前
Kimi K3:Rust封装XTP接口详细教程实践
开发语言·后端·rust
kebeiovo2 小时前
游戏服务端开发:Actor模型详解(Go语言)
开发语言·后端·golang
红烧大青虫3 小时前
setInterval 倒计时实现:60s 验证码发送逻辑
后端·华为·harmonyos·鸿蒙系统
null_173 小时前
IntelliJ IDEA 极致流畅配置方案:Ultra 9 285K + 64GB 内存实测
java·ide·intellij-idea
Herbert_hwt3 小时前
建立Java程序开发
java·开发语言
好好沉淀3 小时前
@ExcelIgnoreUnannotated 和 @AutoMapper 详解
java
小村儿3 小时前
连载14-实战篇--一个半月,我一个人和 Claude Code 搭出一套数字人工程
前端·后端·ai编程
你驴我3 小时前
WhatsApp 多账号下消息已读回执的实时聚合与推送实践
后端·python