码迷,mamicode.com
首页 > 移动开发 > 详细

Spring Boot 获取ApplicationContext

时间:2016-10-12 13:42:38      阅读:940      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.demo;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.ApplicationContextAware;
 6 import org.springframework.stereotype.Component;
 7 
 8 @Component
 9 public class SpringUtils implements ApplicationContextAware {
10     private static ApplicationContext applicationContext = null;
11 
12     @Override
13     public void setApplicationContext(ApplicationContext arg0) throws BeansException {
14         if (SpringUtils.applicationContext == null) {
15             SpringUtils.applicationContext = arg0;
16         }
17     }
18 
19     // 获取applicationContext
20     public static ApplicationContext getApplicationContext() {
21         return applicationContext;
22     }
23 
24     // 通过name获取 Bean.
25     public static Object getBean(String name) {
26         return getApplicationContext().getBean(name);
27     }
28 
29     // 通过class获取Bean.
30     public static <T> T getBean(Class<T> clazz) {
31         return getApplicationContext().getBean(clazz);
32     }
33 
34     // 通过name,以及Clazz返回指定的Bean
35     public static <T> T getBean(String name, Class<T> clazz) {
36         return getApplicationContext().getBean(name, clazz);
37     }
38 
39 }

与Spring Boot启动类同包或其子包

Spring Boot 获取ApplicationContext

标签:

原文地址:http://www.cnblogs.com/imeng/p/5952109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!