spring通過名稱獲取配置的bean例項
阿新 • • 發佈:2019-01-04
/** * 服務工廠介面. * * * */ public interface ServiceFactory extends Serializable { /** * 獲取服務,通過class. * * @param clazz * @return */ public <T> T getService(Class<T> clazz); /** * 獲取服務,通過beanId. * * @param beanId * @param clazz * @return */ public <T> T getService(String beanId, Class<T> clazz); }
import java.io.Serializable; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; /** * * 本地服務工廠. * * */ @Component public class LocalServiceFactory implements Serializable, ServiceFactory, BeanFactoryAware { private static final long serialVersionUID = -4829342420862083368L; private BeanFactory beanFactory; @Override public <T> T getService(Class<T> clazz) { String beanId = this.getServiceName(clazz, null); return beanFactory.getBean(beanId, clazz); } @Override public <T> T getService(String beanId, Class<T> clazz) { beanId = this.getServiceName(clazz, beanId); return beanFactory.getBean(beanId, clazz); } private <T> String getServiceName(final Class<T> clazz, final String serviceName) { String beanName = serviceName; if (!StringUtils.hasLength(serviceName)) { // 得到HelloService beanName = clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1); // 首字母小寫,得到helloService beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1); } return beanName; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
/** * 以靜態變數儲存Spring ApplicationContext, 可在任何程式碼任何地方任何時候中取出ApplicaitonContext. * * */ public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 實現ApplicationContextAware介面的context注入函式, 將其存入靜態變數. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; } /** * 取得儲存在靜態變數中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別. 如果有多個Bean符合Class, 取出第一個. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); Map beanMaps = applicationContext.getBeansOfType(clazz); if (beanMaps != null && !beanMaps.isEmpty()) { return (T) beanMaps.values().iterator().next(); } else { return null; } } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder"); } } }