【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);

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

相关推荐
橘子海全栈攻城狮9 分钟前
【最新源码】养老院系统管理A013
java·spring boot·后端·web安全·微信小程序
逻辑驱动的ken15 分钟前
Java高频面试考点18
java·开发语言·数据库·算法·面试·职场和发展·哈希算法
smallyoung30 分钟前
具有反思能力的 Agentic RAG 实战:用 LangChain4j 实现 CRAG 纠错检索
人工智能·后端
EthanYuan32 分钟前
💡RAG实践:从云知识库迁移到PostgreSQL ,并使用PGVector实现向量存储
后端
冷雨夜中漫步1 小时前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
直奔標竿1 小时前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring
等风来_shy1 小时前
如何写好一个 Skill
后端
one_love_zfl2 小时前
java面试-微服务组件篇
java·微服务·面试
一只大袋鼠2 小时前
Java进阶:CGLIB动态代理解析
java·开发语言
ailab2 小时前
研发人员如何写好 AI 提示词:从“问问题”到“驱动研发闭环”
后端