ApplicationContextAware接口功能大全
下文笔者将讲述ApplicationContextAware接口的作用,如下所示
ApplicationContextAware接口功能
ApplicationContextAware接口是Spring中定义的一个规则 如果我们的类实现了ApplicationContextAware接口后,Spring框架在加载时,会进行相应的处理 主要体现在可以非常方便的获取Spring上下文的信息,如: 获取ApplicationContext中所有bean对象 那么ApplicationContext是什么呢?
ApplicationContext简介
ApplicationContext 是IoC容器 她的底层继承了BeanFactory接口 并在BeanFactory上增加了很多功能 日常开发中,我们通常使用ApplicationContext接口作为Spring上下文
ApplicationContextAware接口示例
编写ApplicationContextAware示例代码
package com.java265.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext spring上下文对象
* @throws BeansException 抛出spring异常
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象
*
* @param name spring配置文件中配置的bean名或注解的名称
* @return 一个以所给名字注册的bean的实例
* @throws BeansException 抛出spring异常
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clazz 需要获取的bean的类型
* @return 该类型的一个在ioc容器中的bean
* @throws BeansException 抛出spring异常
*/
public static <T> T getBean(Class<T> clazz) throws BeansException {
return applicationContext.getBean(clazz);
}
/**
* 如果ioc容器中包含一个与所给名称匹配的bean定义,则返回true否则返回false
*
* @param name ioc容器中注册的bean名称
* @return 存在返回true否则返回false
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
}
ApplicationContextUtil类放入Spring的配置文件中
方法类ApplicationContextUtil放入Bean的配置文件中 <!-- 注入ApplicationContextAware接口实现类,spring上下文环境 --> <bean id="applicationContextUtil" class="com.java265.util.ApplicationContextUtil"/>
ApplicationContextUtil类的使用
public class TestUtil {
public static String test(){
UserServiceImpl s=ApplicationContextUtil.getBean("userServiceImpl");
return s.getInfo();
}
}
注意事项:
UserServiceImpl类也应该交给Spring管理
才会进入Spring容器中
<!-- userServiceImpl-->
<bean id="userServiceImpl" class="com.java265.service.impl.UserServiceImpl"/>
ApplicationContextAware接口在springboot中的使用
由于SpringBoot拥有一套默认的扫描规则,会自动扫描指定包及包下的所有注解
所以SpringBoot中我们只需会类加上
@Component注解
如:UserServiceImpl加上@Service注解
ApplicationContextUtil加上@Component注解
即可实现ApplicationContextAware的效果
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


