SpringBoot——容器工具类SpringContextUtils.java
更多精彩内容,欢送关注我的微信公众号:编程Thinker (code_thinker_666)
<img src=”http://jeff.spring4all.com/FoAxSKtLwp-tLYc4XdMCr9SVT8DU” style=”zoom: 25%;” />
背景
在SpringBoot我的项目中,通常会遇到工具类中调用Spring容器中的Bean,因为工具类通常是静态方法,咱们通常不应用主动注入,这时,就须要一种不主动注入便能够从Spring容器中拿出Bean的工具了,这里我把我日常用的工具类SpringContextUtils.java,分享给大家,心愿能够帮到你。
工具类
git地址:https://gitee.com/learning-wo…
源码如下:
import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* Spring容器工具类
*
* @author chentiefeng
* @date 2020-10-23 11:37
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
/**
* 上下文对象
*/
private static final AppContainer APP_CONTAINER = new AppContainer();
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
APP_CONTAINER.setApplicationContext(applicationContext);
}
/**
* 获取ApplicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return APP_CONTAINER.getApplicationContext();
}
/**
* 通过clazz,从spring容器中获取bean
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 获取某一类型的bean汇合
*
* @param clazz
* @param <T>
* @return
*/
public static <T> Map<String, T> getBeans(Class<T> clazz) {
return getApplicationContext().getBeansOfType(clazz);
}
/**
* 通过name和clazz,从spring容器中获取bean
*
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
/**
* 动态外部类,用于寄存ApplicationContext
*/
@Data
public static class AppContainer {
private ApplicationContext applicationContext;
}
/**
* 获取配置文件配置项的值
*
* @param key 配置项key
*/
public static String getEnvironmentProperty(String key) {
return getApplicationContext().getEnvironment().getProperty(key);
}
/**
* 获取spring.profiles.active
*/
public static String[] getActiveProfile() {
return getApplicationContext().getEnvironment().getActiveProfiles();
}
}
应用示例
/**
* 用户工具类,用于获取用户信息
*
* @author chentiefeng
* @date 2021/2/8 17:38
*/
public class UserUtils {
/**
* 获取以后用户的ID
* @return
*/
public static UUID getCurrentUserId(){
UserService userService = SpringContextUtils.getBeans(UserService.class);
return userService.getCurrentUser().getId();
}
}
本文由博客一文多发平台 OpenWrite 公布!
发表回复