SpringBeanUtil工具类

 1 package com.missy.util;
 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 SpringBeanUtil implements ApplicationContextAware {
10     private static ApplicationContext applicationContext = null;
11     @Override
12     public void setApplicationContext(ApplicationContext applicationContext) throws             
13                 BeansException {
14         SpringBeanUtil.applicationContext = applicationContext;
15     }
16     
17     /**
18      * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
19      */
20     @SuppressWarnings("unchecked")
21     public static <T> T getBean(String name) {
22         if(name == null || applicationContext == null)
23             return null;
24         return (T) applicationContext.getBean(name);
25     }
26  
27     /**
28      * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
29      */
30     public static <T> T getBean(Class<T> clazz) {
31         return applicationContext.getBean(clazz);
32     }
33  
34 }

 调用:

XService  x = SpringBeanUtil.getBean(XService.class);

 

微信公众号:敲代码的小浪漫

欢迎大家关注~

原文地址:https://www.cnblogs.com/ywy8/p/13570444.html