獲取Spring載入的例項bean/獲取註解Beam
1,編寫工具類
package com.cfwx.rox.web.business.essence.util; import java.util.HashMap; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 獲取spring的注入bean 工具類 * @author JSW * */ public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext context = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } /** * 獲取在*.xml檔案中有注入的bean * @param beanName * @return */ @SuppressWarnings("unchecked") public static <T> T getBean(String beanName){ return (T) context.getBean(beanName); } /** * 獲取到的類的例項物件 */ private Map<String, Object> classInstances; /** * 獲取到的類的例項物件 指定spring註解的類物件 */ public Map<String, Object> getClassInstances() { if(this.classInstances == null){ init(); } return this.classInstances; } @SuppressWarnings("static-access") public void init(){ if(this.context == null){ return; } if(this.classInstances == null){ this.classInstances = new HashMap<String,Object>(); } Map<String, Object> beansWithAnnotationMap = this.context.getBeansWithAnnotation(org.springframework.stereotype.Service.class); Class<? extends Object> clazz = null; for(Map.Entry<String, Object> entry : beansWithAnnotationMap.entrySet()){ clazz = entry.getValue().getClass();//獲取到例項物件的class資訊 Class<? extends Object> [] interfaces = clazz.getInterfaces(); for(Class<? extends Object> aInterface : interfaces){ //介面例項名(只是將介面的首字母換成小寫) String aInterfaceSimpleName = getDefaultInstanceName(aInterface); classInstances.put(aInterfaceSimpleName, entry.getValue()); } } } /** * 根據這個類來獲取預設的例項名(預設:將首字母換成小寫) * @param clazz 類資訊 * @return 預設的例項名 */ public static String getDefaultInstanceName(Class<?> clazz) { if (clazz == null) { return null; } String className = clazz.getSimpleName(); String firsrLowerChar = className.substring(0, 1).toLowerCase(); className = firsrLowerChar + className.substring(1); return className; } }
2, application.xml中注入
<bean id="springContextUtil" class="com.cfwx.rox.web.business.essence.util.SpringContextUtil"></bean>
3, web.xml中配置監聽
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>