可以随时拿取spring容器中Bean的工具类
2023-09-27 14:24:48 时间
前言
- 在Spring帮我们管理bean后,编写一些工具类的时候需要从容器中拿到一些对象来做一些操作,比如字典缓存工具类,在没有找到字典缓存时,需要dao对象从数据库load一次,再次存入缓存中。此时需要在util工具类中拿到ioc容器中的dao对象。
原理
spring容器在加载的时候会把ApplicationContext注入到实现了ApplicationContextAware的类中,拿到applicationContext后,可以通过getBean来拿到ioc容器中管理的对象
通过实现DisposableBean接口,在容器消亡时,清除注入的applicationContext.
代码
package com.hyq.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Service
@Lazy(false)
/**
* 获取bean的工具类(通过注入applicationCotnext)
* @author hyq
*
*/
public class SpringUtils implements ApplicationContextAware,DisposableBean
{
public static ApplicationContext applicationContext = null;
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName){
isInjected();
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> requiredType){
isInjected();
return applicationContext.getBean(requiredType);
}
@Override
public void destroy() throws Exception {
System.out.println("springUtils工具类清除注入的applicationContext");
SpringUtils.applicationContext = null;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
System.out.println("springUtils工具类注入的applicationContext");
SpringUtils.applicationContext = applicationContext;
}
/**
* 判断是否注入
* @return
*/
public static void isInjected(){
if(SpringUtils.applicationContext == null){
throw new RuntimeException("springUtils applicationContext is not injected!");
}
}
public static void main(String[] args) {
System.out.println(applicationContext);
}
}
相关文章
- spring注解工具类AnnotatedElementUtils和AnnotationUtils
- 深入分析Spring 与 Spring MVC容器
- spring IOC
- Spring Boot 2.4 Windows Scoop 安装命令行工具
- Spring Boot 2.4 使用 OSX Homebrew 安装 CLI 工具
- 缓存插件 Spring支持EHCache缓存
- Spring 依赖注入方式详解
- 别再自己瞎写工具类了,Spring Boot 内置工具类应有尽有。。。
- Spring 常见 Annotation
- 通过spring工具类获取bean
- Spring工具类:WebApplicationContextUtils
- Spring @Scheduled执行原理解析
- Spring——入门介绍(以版本5.2为例)
- spring成神之路第二十二篇:@Scope、@DependsOn、@ImportResource、@Lazy 详解
- Spring Boot(二) :Redis 使用
- 【工具】Spring项目转化Spring Web项目插件
- CXF整合Spring开发WebService
- Spring Boot中使用Swagger2异常:Illegal DefaultValue 0 for parameter type integer
- XJar: Spring-Boot JAR 包加/解密工具,避免源码泄露以及反编译
- Spring的StringUtils工具类