通过ApplicationContextAware获取上下文ApplicationContext

使用过spring的都会有某些场景使用传统方法获取bean对象比较难,这个时候一般会选择通过构造方法或者参数等形式把bean对象传到使用类中。但是在spring中是提供通过扩展的方式获取spring上下文的方法的,本文就会展示一下如何获取ApplicationContext

  • 下面demo代码

实现工具类ApplicationContextUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.zw.dubbo.application.context.aware;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtil implements ApplicationContextAware {

private static ApplicationContext applicationContext;

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

public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}

把ApplicationContextUtil注入到bean容器中, ApplicationContextUtil.xml

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

<bean id="applicationContextUtil" class="com.zw.dubbo.application.context.aware.ApplicationContextUtil"/>
</beans>

使用工具类获取bean对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.zw.dubbo.application.context.aware;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestApplicationContextUtil {

public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:ApplicationContextUtil.xml"});
context.start();
ApplicationContext applicationContext = ApplicationContextUtil.getApplicationContext();
System.out.println("返回结果:" + applicationContext.toString());
}
}

程序执行结果

1
2
3
4
10:34:47.696 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ea30797
10:34:48.092 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [ApplicationContextUtil.xml]
10:34:48.191 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'applicationContextUtil'
返回结果:org.springframework.context.support.ClassPathXmlApplicationContext@ea30797, started on Sat Feb 25 10:34:47 CST 2023