从Spring上下文中获取bean实例:
复制代码
1
2
3
4
5
6
7
8
9private JWTConfig jwtConfig=null; public JWTConfig getJWTConfig(){ if(jwtConfig==null){ //根据类名获取 jwtConfig = SpringContextUtil.getBeanByClass(JWTConfig.class); } return jwtConfig; }
Spring上下文工具类:
复制代码
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@Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } /** * 获得spring上下文 * @return ApplicationContext spring上下文 */ public static ApplicationContext getApplicationContext(){ return applicationContext; } /*** * 根据一个bean的id获取配置文件中相应的bean */ public static Object getBean(String beanId) throws BeansException { if (applicationContext.containsBean(beanId)) { return applicationContext.getBean(beanId); } return null; } /*** * 根据一个bean的类型获取配置文件中相应的bean */ public static <T> T getBeanByClass(Class<T> requiredType) throws BeansException { return applicationContext.getBean(requiredType); } /** * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true */ public static boolean containsBean(String name) { return applicationContext.containsBean(name); } }
最后欢迎大家使用帮助记忆网站:助记宝
最后
以上就是文静冬天最近收集整理的关于Springboot普通类如何获取bean实例?的全部内容,更多相关Springboot普通类如何获取bean实例内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复