0%

spring | ApplicationContextAware 接口

ApplicationContextAware 实现与应用。

ApplicationContext

Spring 容器是生成Bean实例的工厂,并管理容器中的 Bean 。生活中我们一般会把生产产品的地方称为工厂,而在这里 bean 对象的地方官方取名为 BeanFactory ,直译 Bean 工厂(com.springframework.beans.factory.BeanFactory ),我们一般称 BeanFactory 为 IoC 容器,而称 ApplicationContext 为应用上下文。

BeanFactory 提供了 OC 容器最基本的形式,给具体的IOC容器的实现提供了规范,BeanFactory 负责配置、创建、管理 Bean 等基本功能

ApplicationContext 的中文意思是“应用前后关系”,它继承自 BeanFactory 接口,除了包含 BeanFactory 的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持,被推荐为 Java EE 应用之首选,可应用在 Java APP 与 Java Web 中。

ApplicationContextAware

实现 ApplicationContextAware 接口之后,系统启动时就可以自动给我们的服务注入 applicationContext 对象(自动调用了接口中的 setApplicationContext 方法),我们就可以获取到 ApplicationContext 里的所有信息了。

ps: 在 Spring 框架中,如果一个类实现了 org.springframework.context.ApplicationContextAware 接口,那么 Spring 容器在实例化这个类的时候会自动调用其 setApplicationContext 方法,从而将 Spring 的 ApplicationContext 对象传递给该类,以便在类中访问应用程序上下文中的 bean。

当 Spring 容器检测到一个类实现了这个接口,它会在实例化该类之后,调用 setApplicationContext 方法,将应用程序上下文作为参数传递给这个方法。

这个机制允许你在 Spring 托管的组件中获得对 Spring 容器的引用,从而可以访问和操作容器中的其他 bean。这在某些情况下非常有用,例如,你可能需要在自定义组件中访问其他 bean,或者对应用程序上下文进行一些特定的操作。

总之,Spring 通过自动调用 setApplicationContext 方法,允许你方便地获取对应用程序上下文的引用。这是 Spring IoC(控制反转)和依赖注入的一个示例,它使得你的组件能够以松散耦合的方式与 Spring 容器协作。

注意:实现ApplicationContextAware接口的类需要交给spring管理,使用 @Component 或者在配置文件声明 bean

我们获取 ApplicationContext ,一般是用来获取 bean 的,ApplicationContext 有一个 getBean 方法,此方法继承自 BeanFactory

1
T getBean(Class requiredType) throws BeansException;

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.cbi.rpmc.bean;

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


@Component

public class SpringUtilsT implements ApplicationContextAware {


private static ApplicationContext applicationContext = null;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

if (SpringUtilsT.applicationContext == null) {

SpringUtilsT.applicationContext = applicationContext;

}

}

//获取applicationContext

public static ApplicationContext getApplicationContext() {

return applicationContext;

}


//通过name获取 Bean.

public static Object getBean(String name) {

return getApplicationContext().getBean(name);

}


//通过class获取Bean.

public static <T> T getBean(Class<T> clazz) {

return getApplicationContext().getBean(clazz);

}


//通过name,以及Clazz返回指定的Bean

public static <T> T getBean(String name, Class<T> clazz) {

return getApplicationContext().getBean(name, clazz);

}

}

使用场景

如果我们在 spring boot 中直接 new 出来的话,是进不了 IOC 里面的,但是,通过上面进行获取的是 IOC 里面的实例。

具体可以看

请我喝杯咖啡吧~